Data Structures and Algorithms
C++ Exceptions

C++ defines a mechanism that is somewhat similar to Ada's exception mechanism.

C++ allows you to execute a throw statement when an error is detected. When a throw is invoked, control jumps immediately to a catch routine.

First you define a try block which encloses the "normal" (no exception) code. The try block is followed by a number of catch blocks: if code in the try block throws an exception, it is caught by one of the catch blocks.

try {
    classX x;
    x.mangle( 2 );
    x.straighten( -2 );
catch( const char *string ) { ..... }
catch( RangeErr &re ) { .... }
catch( ... ) {
    // catches any other error
classX's constructor, mangle and straighten methods contain throw statements when problems are encountered:
classX::mangle( int degree ) {
     if ( degree > MAX_MANGLE )
         throw "Can't mangle this much!";
     .... // Normal code for mangle
The throw causes control to jump straight out of the mangle method to the catch block, skipping all subsequent statements in the try block.

However, like much of C++, the rules which are used to associate a throw with the correct catch are too complex to contemplate. Stroustroup attempted to make the throw like a general method invocation with parameters, overloading, etc, etc.

Historical note: many early C++ compilers did not implement the throw/catch pair, (possibly because of the complexity alluded to above!) and some textbooks avoid it - or relegate it to the last few pages!

Basically, like a lot of C++ features, the throw/catch mechanism is best used in a very simple way, eg by providing a single catch block with a single int or enum parameter! Ada's simple and clean mechanism may lack some power (an exception handler can't be passed a parameter), but it's a lot easier to understand and use!

Continue on to Java Exceptions
Back to the Table of Contents
© John Morris, 1998