C++ Programming Guide

Specifying Exceptions to Be Thrown

A function declaration can include an exception specification, a list of exceptions that a function may throw, directly or indirectly.

The two following declarations indicate to the caller that the function f1 generates only exceptions that can be caught by a handler of type X, and that the function f2 generates only exceptions that can be caught by handlers of type W, Y, or Z:


void f1(int) throw(X);
void f2(int) throw(W,Y,Z);

A variation on the previous example is:


void f3(int) throw(); // empty parentheses

This declaration guarantees that no exception is generated by the function f3. If a function exits via any exception that is not allowed by an exception specification, it results in a call to the predefined function unexpected(). By default, unexpected() calls abort() to exit the program. You can change this default behavior by calling the set_unexpected() function. See "set_unexpected() ".

The check for unexpected exceptions is done at program execution time, not at compile time. Even if it appears that a disallowed exception might be thrown, there is no error unless the disallowed exception is actually thrown at runtime.

The compiler can, however, eliminate unnecessary checking in some simple cases. For instance, no checking for f is generated in the following example.


void foo(int) throw(x);
void f(int) throw(x);
{
	foo(13);
}

The absence of an exception specification allows any exception to be thrown.