< previous page page_424 next page >

Page 424
How Exceptions Are Used.
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

d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
1:      #include <iostream.h>
2:
3:      const int DefaultSize = 10;
4:
5:      // define the exception class
d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
continues

 
< previous page page_424 next page >

If you like this book, buy it!