Sams Teach Yourself C++ in 21 Days

(singke) #1
Handling Errors and Exceptions 729

20


If the exception reaches all the way to the beginning of the program (main()) and is still
not caught, a built-in handler is called that terminates the program.
It is important to note that the exception unwinding of the stack is a one-way street. As it
progresses, the stack is unwound and objects on the stack are destroyed. There is no
going back: After the exception is handled, the program continues after the tryblock of
the catchstatement that handled the exception.
Thus, in Listing 20.4, execution continues on line 101, the first line after the tryblock of
the catchstatement that handled the xBoundaryexception. Remember that when an
exception is raised, program flow continues after the catchblock, not after the point
where the exception was thrown.

Using More Than One catchSpecification ..................................................


It is possible for more than one condition to cause an exception. In this case, the catch
statements can be lined up one after another, much like the conditions in a switch state-
ment. The equivalent to the default statement is the “catch everything” statement, indi-
cated by catch(...). Listing 20.5 illustrates multiple exception conditions.

LISTING20.5 Multiple Exceptions


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&);
23:
24: // define the exception classes
Free download pdf