|
|
|
|
|
|
|
try blocks are created to surround areas of code that may have a problem. For example: |
|
|
|
|
|
|
|
|
try
{
SomeDangerousFunction();
} |
|
|
|
|
|
|
|
|
catch blocks handle the exceptions thrown in the try block. For example: |
|
|
|
|
|
|
|
|
try
{
SomeDangerousFunction();
}
catch (OutOfMemory)
{
// take some actions
}
catch (FileNotFound)
{
// take other action
} |
|
|
|
|
|
|
|
|
The basic steps in using exceptions are: |
|
|
|
|
|
|
|
|
1. Identify those areas of the program in which you begin an operation that might raise an exception, and put them in try blocks. |
|
|
|
|
|
|
|
|
2. Create catch blocks to catch the exceptions if they are thrown, to clean up allocated memory, and to inform the user as appropriate. Listing 24.1 illustrates the use of both try blocks and catch blocks. |
|
|
|
|
|
|
|
|
Exceptions are objects used to transmit information about a problem. |
|
|
|
|
|
|
|
|
A try block is a block, surrounded by braces, in which an exception may be thrown. |
|
|
|
|
|
|
|
|
A catch block is the block immediately following a try block, in which exceptions are handled. |
|
|
|
|
|
|
|
|
When an exception is thrown (or raised), control transfers to the catch block immediately following the current try block. |
|
|
|
|
|
|
|
|
LISTING 24.1 RAISING AN EXCEPTION |
|
|
|
 |
|
|
|
|
1: #include <iostream.h>
2:
3: const int DefaultSize = 10;
4:
5: // define the exception class |
|
|
|
 |
|
|
|
|
continues |
|
|
|
|
|