8 Exception Handling

Exception handling provides a standard mechanism for coding responses to runtime errors or exceptions.

This chapter discusses the following topics:

“Exception Handling in C++” (page 161)

“Exception Handling as Defined by the ANSI/ISO C++ International Standard” (page 162)

“Basic Exception Handling Example” (page 162)

“Function Try Block Examples” (page 162)

“Debugging Exception Handling” (page 163)

“Performance Considerations” (page 163)

Exception Handling

Exception handling provides a standard mechanism for coding responses to runtime errors or exceptions. Exception handling is on by default. To turn it off, you must use the +noeh option.

If your executable throws no exceptions, object files compiled with and without the +noeh option can be mixed freely. However, in an executable which throws exceptions (HP aC++ runtime libraries throw exceptions), you must be certain that no exception is thrown in your application which will unwind through a function compiled without the exception handling option turned on.

In order to prevent this, the call graph for the program must never have calls from functions compiled without exception handling to functions compiled with exception handling (either direct calls or calls made through a callback mechanism). If such calls do exist, and an exception is thrown, the unwinding can cause:

Non-destruction of local objects (including compiler generated temporaries).

Memory leaks when destructors are not executed.

Runtime errors when no catch clause is found.

Exception Handling in C++

Following is an overview of the elements of C++ exception handling:

A try block encloses (logically) code that can cause an exception that you want to catch.

A catch clause, which immediately follows the try block, handles an exception of the type that can occur in the try block. The catch clause is the exception handler. You can have multiple catch clauses associated with a try block.

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 161