Exception Handling - C++
Introduction
An exception may be regarded as a predictable, but somewhat unusual
condition that may occur during runtime. Failure to catch and deal with
an exception, may prove catostrosphic.
C++ supports various exception handling functions and classes.
Alternately, user-defined exception handling can declared.
Exception may occur as a result of any of the following:
- Memory exhaustion
- The openning or closing of files
- Out of bounds array subscripts
- Arithmetic overflow or underflow
- To some extent, invalid function parameters
- Inappropriate value stated in the #define
statement
What to do if an exception occurs:
- Let the program crash?
- Inform the user and exit gracefully?
- Inform the user and let the user try to recover from the
exception and continue?
- Let the program take corrective measures without disturbing
the user?
One of the best solutions is to use the latter measure.
Handling Exceptions
Exception handling revolves around:
- A try block
- A throw statement
- One or more A catch blocks
The catch block must follow immediately after the
try block.
The general procedure is:
try{
throw exception_parameter;
}
catch( < data_type parameter)
{
// C++ code to handle exception
}
Features of Exception Handling
Exception handler - the argument in the catch function
header.
If an exception occurs, the flow of the program is
interrupted, and the exception is thrown.
If a throw is made, the
program searches for an associated handler. If no handle is found, the
function terminate() is called, which in tern calls the
function abort() , and the program stops.
Multiple Catch Blocks
A try block may have multiple
catch blocks. Each catch block must be unique in terms of the number of
parameters, the order of the parameters, and the type of each parameter.
Handling All Exceptions
A catch block may catch any type of exception by initiating the following
statement pattern:
catch( ... )
{
// C++ code to handle exception
}
This catch block must be the last block in a series of catch blocks.
Throwing Exception from Function other than main
Exceptions can be thrown from functions other than main, because within a
function the exception may occur. To do this, instantiate the following
pattern:
rt _name::function(argument_list) {
try{
throw exception_parameter;
}
catch( < data_type parameter)
{
// C++ code to handle exception
}
}
Exception Specification
A function may specify excatly what set of exceptions it can throw. To
do this, instantiate the following pattern:
rt _name::function(argument_list)
throw(exception_specification_list) {
try{
throw exception_parameter;
}
catch( < data_type parameter)
{
// C++ code to handle exception
}
}
Note: if the exception parameter is not in the exception specification
list then the function unexpected() is called.
Go Back To Schedule