Sams Teach Yourself C++ in 21 Days

(singke) #1
119: cout << “You asked for an Array of zero objects!” << endl;
120: cout << “Received “ << theException.GetSize() << endl;
121: }
122: catch (Array::xTooBig theException)
123: {
124: cout << “This Array is too big...” << endl;
125: cout << “Received “ << theException.GetSize() << endl;
126: }
127: catch (Array::xTooSmall theException)
128: {
129: cout << “This Array is too small...” << endl;
130: cout << “Received “ << theException.GetSize() << endl;
131: }
132: catch (...)
133: {
134: cout << “Something went wrong, but I’ve no idea what!\n”;
135: }
136: cout << “Done.” << endl;
137: return 0;
138: }

This array is too small...
Received 9
Done.
The declaration of xSizehas been modified to include a member variable,
itsSize, on line 33 and a member function,GetSize(), on line 31. In addition, a
constructor has been added that takes an integer and initializes the member variable, as
shown on line 29.
The derived classes declare a constructor that does nothing but initialize the base class.
No other functions were declared, in part to save space in the listing.
The catchstatements on lines 113–135 are modified to name the exception they catch,
theException, and to use this object to access the data stored in itsSize.

OUTPUT


738 Day 20


LISTING20.7 continued

ANALYSIS

Keep in mind that if you are constructing an exception, it is because an
exception has been raised: Something has gone wrong, and your exception
should be careful not to kick off the same problem. Therefore, if you are
creating an OutOfMemoryexception, you probably don’t want to allocate
memory in its constructor.

NOTE
Free download pdf