|
|
|
|
|
|
|
Programmers use powerful compilers and sprinkle their code with asserts to catch programming errors. They use design reviews and exhaustive testing to find logic errors. |
|
|
|
|
|
|
|
|
Exceptions are different, however. You can't eliminate exceptional circumstances; you can only prepare for them. Your users will run out of memory from time to time, and the only question is what you will do. Your choices are these: |
|
|
|
|
|
|
|
|
Inform the user and exit gracefully. |
|
|
|
|
|
|
|
|
Inform the user and allow the user to try to recover and continue. |
|
|
|
|
|
|
|
|
Take corrective action and continue without disturbing the user. |
|
|
|
|
|
|
|
|
Although it is not necessary or even desirable for every program you write to automatically and silently recover from all exceptional circumstances, it is clear that you must do better than crashing. |
|
|
|
|
|
|
|
|
C++ exception handling provides a type-safe, integrated method for coping with the predictable but unusual conditions that arise while running a program. |
|
|
|
|
|
|
|
|
In C++, an exception is an object that is passed from the area of code where a problem occurs to the part of the code that is going to handle the problem. The type of the exception determines which area of code will handle the problem; and the contents of the object thrown, if any, may be used to provide feedback to the user. |
|
|
|
|
|
|
|
|
The basic idea behind exceptions is fairly straightforward: |
|
|
|
|
|
|
|
|
The actual allocation of resources (for example, the allocation of memory or the locking of a file) is usually done at a very low level in the program. |
|
|
|
|
|
|
|
|
The logic of what to do when an operation fails, memory cannot be allocated, or a file cannot be locked is usually high in the program, with the code for interacting with the user. |
|
|
|
|
|
|
|
|
Exceptions provide an express path from the code that allocates resources to the code that can handle the error condition. If there are intervening layers of functions, they are given an opportunity to clean up memory allocations, but are not required to include code whose only purpose is to pass along the error condition. |
|
|
|
|
|