Listing 20.1 was actually designed to crash; however, if you had asked the user
to enter two numbers, he could have encountered the same results.
In lines 8 and 9, two integer variables are declared and given values. You could just as
easily have prompted the user for these two numbers or read them from a file. In lines
11, 14, and 16, these numbers are used in math operations. Specifically, they are used for
division. In lines 11 and 16, there are no issues; however, line 14 has a serious problem.
Division by zero causes an exceptional problem to occur—a crash. The program ends
and most likely an exception is displayed by the operating system.
Although it is not always necessary (or even desirable) to automatically and silently
recover from all exceptional circumstances, it is clear that you must do better than this
program. You can’t simply let your program crash.
C++ exception handling provides a type-safe, integrated method for coping with the pre-
dictable but unusual conditions that arise while running a program.
The Idea Behind Exceptions................................................................................
The basic idea behind exceptions is fairly straightforward:
- The computer tries to run a piece of code. This code might try to allocate resources
such as memory, might try to lock a file, or any of a variety of tasks. - Logic (code) is included to be prepared in case the code you are trying to execute
fails for some exceptional reason. For example, you would include code to catch
any issues, such as memory not being allocated, a file being unable to be locked, or
any of a variety of other issues. - In case your code is being used by other code (for instance, one function calling
another), you also need a mechanism to pass information about any problems
(exceptions) from your level, up to the next. There should be a path from the code
where an issue occurs to the code that can handle the error condition. If intervening
layers of functions exist, they should be given an opportunity to clean the issue but
should not be required to include code whose only purpose is to pass along the
error condition.
Exception handling makes all three of these points come together, and they do it in a rel-
atively straightforward manner.
718 Day 20
This program might display the preceding output to the console; however, it
will most likely immediately crash afterward.
CAUTION
ANALYSIS