Unlike the prior listing, this listing takes more control of its exceptions.
Although this isn’t the best use of exceptions, it clearly illustrates using the
throwstatement.
In line 17, a check is done to see if the value of bottomis equal to zero. If it is, an excep-
tion is thrown. In this case, the exception is a string value.
On line 24, a catchstatement starts a handler. This handler is looking for a constant
character pointer. With exceptions, strings are matched to a constant character pointer, so
the handler starting in line 24 catches the throw in line 18. In line 26, the string that was
passed is displayed between asterisks. Line 27 is the closing brace, which indicates the
end of the handler, so control goes to the first line following the catchstatements and
the program continues to the end.
If your exception had been a more serious problem, you could have exited the applica-
tion after printing the message in line 26. If you throw your exception in a function that
was called by another function, you could have passed the exception up. To pass on an
exception, you can simply call the throwcommand without any parameter. This causes
the existing exception to be rethrown from the current location.
Creating an Exception Class ..........................................................................
You can create much more complex classes for throwing an exception. Listing 20.4 pre-
sents a somewhat stripped-down Arrayclass, based on the template developed on Day
19, “Templates.”
LISTING20.4 Throwing an Exception
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:
724 Day 20
ANALYSIS