Logo Data Structures and Algorithms with Object-Oriented Design Patterns in C++
next up previous contents index

Exceptions

 

Sometimes unexpected situations arise during the execution of a program. Careful programmers write code that detects errors and deals with them appropriately. However, a simple algorithm can become unintelligible when error-checking is added because the error-checking code can obscure the normal operation of the algorithm.

Exceptions  provide a clean way to detect and handle unexpected situations. When a program detects an error, it throws  an exception. When an exception is thrown, control is transfered to the appropriate exception handler . By defining a function that catches the exception, the programmer can write the code to handle the error.

In C++, an exception is an object. Typically exceptions are derived (directly or indirectly) from the base class called exception which is defined in the C++ standard library header file called <exception>.

A function throws an exception by using the throw statement:

class domain_error : public exception {};

void f ()
{
    // ...
    throw domain_error ();
}
The throw statement is similar to a return statement. A return statement represents the normal termination of a function and the object returned matches the return value of the function. A throw statement represents the abnormal termination of a function and the object thrown represents the type of error encountered.

Exception handlers are defined using a try block:

void g ()
{
    try {
        f ();
    }
    catch (domain_error) {
        // exception handler
    }
    catch (range_error) {
        // exception handler
    }
}
The body of the try block is executed either until an exception is thrown or until it terminates normally.

One or more exception handlers follow a try block. Each exception handler consists of a catch clause which specifies the exceptions to be caught, and a block of code, which is executed when the exception occurs. When the body of the try block throws an exception for which an exception is defined, control is transfered to the body of the exception handler.

In this example, the exception was thrown by the function f() and caught by the function g(). In general when an exception is thrown, the chain of functions called is searched in reverse (from caller to callee) to find the closest matching catch statement. As the stack of called functions unwinds, the destructors for the local variables declared in those functions are automatically executed. When a program throws an exception that is not caught, the program terminates.


next up previous contents index

Bruno Copyright © 1997 by Bruno R. Preiss, P.Eng. All rights reserved.