in the previous example, the exception is checked to see if it matches the indicated type.
If not, the next catchstatement is checked, and so on, until either a match is found or
something other than a catchblock is found. When the first match is found, that catch
block is executed. Unless you really intended to let other types of exceptions through, it
is always a good idea to have the last catchuse the ellipse parameter.
720 Day 20
NOTE A catchblock is also called a handler because it can handle an exception.
You can look at the catchblocks as being like overloaded functions. When
the matching signature is found, that function is executed.
NOTE
The basic steps in handling exceptions are
- Identify those areas of the program in which you begin an operation that might
raise an exception, and put them in tryblocks. - Create catchblocks to catch the exceptions if they are thrown. You can either cre-
ate a catchfor a specific type of exception (by specifying a typed parameter for
the catchblock) or all exceptions (by using an ellipses (...) as the parameter).
Listing 20.2 adds basic exception handling to Listing 20.1. You can see this with the use
of both a tryblock and a catchblock.
Some very old compilers do not support exceptions. Exceptions are part of
the ANSI C++ standard, however, and every compiler vendor’s latest edition
fully supports exceptions. If you have an older compiler, you won’t be able
to compile and run the exercises in today’s lesson. It’s still a good idea to
read through the entire chapter, however, and return to this material when
you upgrade your compiler.
NOTE
LISTING20.2 Catching an Exception
0: // trying and catching
1: #include <iostream>
2: using namespace std;
3:
4: const int DefaultSize = 10;
5: