Handling Errors and Exceptions 745
20
105: catch (xBoundary)
106: {
107: cout << “Unable to process your input!” << endl;
108: }
109: catch (Array<int>::xSize)
110: {
111: cout << “Bad Size!” << endl;
112: }
113:
114: cout << “Done.” << endl;
115: return 0;
116: }
Bad Size!
Done.
The first exception,xBoundary, is declared outside the template definition on line
- The second exception,xSize, is declared from within the definition of the
template on line 28.
The exception xBoundaryis not tied to the template class, but it can be used the same as
any other class. xSizeis tied to the template and must be called based on the instantiated
Array. You can see the difference in the syntax for the two catchstatements. Line 105
shows catch (xBoundary), but line 109 shows catch (Array::xSize). The latter
is tied to the instantiation of an integer Array.
Exceptions Without Errors ..................................................................................
When C++ programmers get together for a virtual beer in the cyberspace bar after work,
talk often turns to whether exceptions should be used for routine conditions. Some main-
tain that by their nature, exceptions should be reserved for those predictable but excep-
tional circumstances (hence the name!) that a programmer must anticipate, but that are
not part of the routine processing of the code.
Others point out that exceptions offer a powerful and clean way to return through many
layers of function calls without danger of memory leaks. A frequent example is this: The
user requests an action in a graphical user interface (GUI) environment. The part of the
code that catches the request must call a member function on a dialog manager, which, in
turn, calls code that processes the request, which calls code that decides which dialog
box to use, which, in turn, calls code to put up the dialog box, which finally calls code
that processes the user’s input. If the user clicks Cancel, the code must return to the very
first calling method where the original request was handled.
OUTPUT
LISTING20.9 continued
ANALYSIS