accessed. This causes the test on line 66 to fail, and operator[]raises an xBoundary
exception on line 67.
Program control switches to the catchblock on line 99, and the exception is caught or
handled by the catchon the same line, which prints an error message. Program flow
drops through to the end of the catchblock on line 102.
Placing tryBlocks and catchBlocks ................................................................
Figuring out where to put your tryblocks can be hard: It is not always obvious which
actions might raise an exception. The next question is where to catch the exception. It
might be that you’ll want to throw all memory exceptions where the memory is allo-
cated, but you’ll want to catch the exceptions high in the program where you deal with
the user interface.
When trying to determine tryblock locations, look to where you allocate memory or use
resources. Other things to look for are out-of-bounds errors, illegal input, and so forth. At
the very least, put a try/catcharound all of the code in main(). try/catchusually
belongs in high-level functions, particularly those that know about the program’s user
interface. For instance, a utility class should not generally catch exceptions that need to
be reported to the user because it might be used in windowed programs or console pro-
grams, or even in programs that communicate with users via the Web or messaging.
How Catching Exceptions Work..........................................................................
Here’s how it works: When an exception is thrown, the call stack is examined. The call
stack is the list of function calls created when one part of the program invokes another
function.
The call stack tracks the execution path. If main()calls the function
Animal::GetFavoriteFood(), and GetFavoriteFood()calls
Animal::LookupPreferences(), which, in turn, calls fstream::operator>>(), all these
are on the call stack. A recursive function might be on the call stack many times.
The exception is passed up the call stack to each enclosing block. This is called
“unwinding the stack.” As the stack is unwound, the destructors for local objects on the
stack are invoked, and the objects are destroyed.
One or more catchstatements follow each tryblock. If the exception matches one of
the catchstatements, it is considered to be handled by having that statement execute. If
it doesn’t match any, the unwinding of the stack continues.
728 Day 20