Handling Errors and Exceptions 719
20
The Parts of Exception Handling ..................................................................
To handle exceptions, you have to first identify that you want a particular piece of code
to be watched for any exceptions. This is accomplished by using a tryblock.
You should create a tryblock around any area of code that you believe has the potential
to cause a problem. The basic format of the tryblock is:
try
{
SomeDangerousFunction();
}
catch (...)
{
}
In this case, when SomeDangerousFunction()executes, if any exception occurs, it is
noted and caught. Adding the keyword tryand the braces is all that is required to have
your program start watching for exceptions. Of course, if an exception occurs, then you
need to act upon it.
When the code within a tryblock is executed, if an exception occurs, the exception is
said to be “thrown.” Thrown exceptions can then be caught, and as shown previously,
you catchan exception with a catchblock! When an exception is thrown, control trans-
fers to the appropriate catchblock following the current tryblock. In the previous
example, the ellipse (...) refers to any exception. But you can also catch specific types
of exceptions. To do this, you use one or more catchblocks following your tryblock.
For example,
try
{
SomeDangerousFunction();
}
catch(OutOfMemory)
{
// take some actions
}
catch(FileNotFound)
{
// take other action
}
catch (...)
{
}
In this example, when SomeDangerousFunction()is executed, there will be handling in
case there is an exception. If an exception is thrown, it is sent to the first catchblock
immediately following the tryblock. If that catchblock has a type parameter, like those