Handling Errors and Exceptions 735
20
The Arrayis created with size zero, but what’s this? The wrong exception appears to be
caught! Examine the catchblock carefully, however, and you will find that it looks for
an exception of type xTooSmallbefore it looks for an exception of type xZero. Because
an xZeroobject is thrown and an xZeroobject is an xTooSmallobject, it is caught by the
handler for xTooSmall. After being handled, the exception is not passed on to the other
handlers, so the handler for xZerois never called.
The solution to this problem is to carefully order the handlers so that the most specific
handlers come first and the less specific handlers come later. In this particular example,
switching the placement of the two handlers xZeroand xTooSmallfixes the problem.
Data in Exceptions and Naming Exception Objects ..........................................
Often, you will want to know more than just what type of exception was thrown so you
can respond properly to the error. Exception classes are the same as any other class. You
are free to provide data, initialize that data in the constructor, and read that data at any
time. Listing 20.7 illustrates how to do this.
LISTING20.7 Getting Data Out of an Exception Object
0: #include <iostream>
1: using namespace std;
2:
3: const int DefaultSize = 10;
4:
5: class Array
6: {
7: public:
8: // constructors
9: Array(int itsSize = DefaultSize);
10: Array(const Array &rhs);
11: ~Array() { delete [] pType;}
12:
13: // operators
14: Array& operator=(const Array&);
15: int& operator[](int offSet);
16: const int& operator[](int offSet) const;
17:
18: // accessors
19: int GetitsSize() const { return itsSize; }
20:
21: // friend function
22: friend ostream& operator<< (ostream&, const Array&);