Exception Handling as Defined by the ANSI/ISO C++ International Standard

The Standard C++ Library provides classes that C++ programs can use for reporting errors. These classes are defined in the header file <stdexcept> and described in the ANSI/ISO C++ International Standard.

The class, exception, is the base class for object types thrown by the Standard C++ Library components and certain expressions.

The class, runtime_error, defines errors due to events beyond the scope of the program.

The class, logic_error, defines errors in the internal logic of the program.

Basic Exception Handling Example

The simple program shown here illustrates exception handling concepts. This program contains a try block (from which a range error is thrown) and a catch clause, which prints the operand of the throw.

This program also uses the runtime_error class defined in the Standard C++ Library to report a range error.

#include <stdexcept> #include <iostream.h> #include <string> void fx ()

{

// details omited

throw range_error(string(“some info”));

}

int main ( )

{

try {

fx ();

}catch (runtime_error& r) { cout <<r.what() << ‘\n’;

}

}

Function Try Block Examples

A function can catch exceptions thrown during its execution by associating catch handlers with its body, using a function try block. Note the difference between the following example and the previous exception handling example. In this case, the try keyword comes before the function body’s opening brace, and the catch handler comes after the function body’s closing brace.

#include <stdexcept> #include <iostream.h> #include <string> void fx ()

{

// .......

throw range_error(string(“some info”));

}

 

int main ( )

 

try {

 

fx ();

 

}

 

catch (runtime_error& r) {

 

cout <<r.what() << ‘\n’;

}

Function try blocks are sometimes necessary with class constructor destruction. A function try block is the only means of ensuring that all exceptions thrown during the construction of an object are caught within the constructor. For example,

162 Exception Handling