Sams Teach Yourself C++ in 21 Days

(singke) #1
138: {
139: cout << “Unable to process your input!” << endl;
140: }
141: catch (Array::xSize& theException)
142: {
143: theException.PrintError();
144: }
145: catch (...)
146: {
147: cout << “Something went wrong!” << endl;
148: }
149: cout << “Done.” << endl;
150: return 0;
151: }

Too small! Received: 9
Done.
Listing 20.8 declares a virtual method on lines 33–37 in the xSizeclass,
PrintError(), that prints an error message and the actual size of the class. This
is overridden in each of the derived classes.
On line 141 in the exception handler, the exception object is declared to be a reference.
When PrintError()is called with a reference to an object, polymorphism causes the
correct version of PrintError()to be invoked. The code is cleaner, easier to understand,
and easier to maintain.

Exceptions and Templates ..................................................................................


When creating exceptions to work with templates, you have a choice: You can create an
exception for each instance of the template, or you can use exception classes declared
outside the template declaration. Listing 20.9 illustrates both approaches.

LISTING20.9 Using Exceptions with Templates
0: #include <iostream>
1: using namespace std;
2:
3: const int DefaultSize = 10;
4: class xBoundary {};
5:
6: template <class T>
7: class Array
8: {

OUTPUT


742 Day 20


LISTING20.8 continued

ANALYSIS
Free download pdf