HP aC++/HP C A.06.20 Programmer's Guide

If an error occurs, code in the try block throws an exception to an appropriate catch
clause. The catch clause is ignored if an error does not occur.
When an exception is thrown, control is transferred to the nearest handler defined
to handle that type of exception. Nearest means the handler whose try block was
most recently entered by the thread of control, and not yet exited.
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
210 Exception Handling