Sams Teach Yourself C++ in 21 Days

(singke) #1
Handling Errors and Exceptions 731

20


73: int main()
74: {
75: try
76: {
77: Array intArray(0);
78: for (int j = 0; j < 100; j++)
79: {
80: intArray[j] = j;
81: cout << “intArray[“ << j << “] okay...” << endl;
82: }
83: }
84: catch (Array::xBoundary)
85: {
86: cout << “Unable to process your input!” << endl;
87: }
88: catch (Array::xTooBig)
89: {
90: cout << “This array is too big...” << endl;
91: }
92: catch (Array::xTooSmall)
93: {
94: cout << “This array is too small...” << endl;
95: }
96: catch (Array::xZero)
97: {
98: cout << “You asked for an array”;
99: cout << “ of zero objects!” << endl;
100: }
101: catch (...)
102: {
103: cout << “Something went wrong!” << endl;
104: }
105: cout << “Done.” << endl;
106: return 0;
107: }

You asked for an array of zero objects!
Done.
Four new classes are created in lines 25–29:xTooBig,xTooSmall,xZero, and
xNegative. In the constructor, on lines 56–71, the size passed to the constructor
is examined. If it’s too big, too small, negative, or zero, an exception is thrown.
The tryblock is changed to include catchstatements for each condition other than
negative, which is caught by the “catch everything” statement catch(...), shown on
line 101.

OUTPUT


LISTING20.5 continued


ANALYSIS
Free download pdf