C++ provides a mechanism to ensure that a given function is
limited to throwing only a specified list of exceptions. An
exception specification at the beginning of any function acts as
a guarantee to the function's caller that the function will not
directly or indirectly throw any exception not contained in the
exception specification. For example, a function:
void translate() throw(unknown_word,bad_grammar) { /* ... */ }
explicitly states that it will not throw any exception other than unknown _word or bad_grammar. The function translate() must handle any exceptions thrown by functions it might call, unless those exceptions are specified in the exception specification of translate(). If an exception is thrown by a function called by translate() and the exception is not handled by translate() or contained in the exception specification of translate(), unexpected() is called.
If an exception is thrown from a function that has not specified the thrown exception in its exception specification, the result is a call to the function unexpected().
A function with an empty throw() specification guarantees that the function will not throw any exceptions. A function without an exception specification allows any object to be thrown from the function.
The compiler does not prevent an exception specification from defining a more limited set of valid exceptions than the set of exceptions the function may actually throw. Such an error is detected only at run time, and only if the unspecified exception is thrown.
If a function with an exception specification calls a subfunction with a less restrictive exception specification (one that contains more objects than the calling function's exception specification), any thrown objects from within the subfunction that are not handled by the subfunction, and that are not part of the outer function's specification list, must be handled within the outer function. If the outer function fails to handle an exception not in its exception specification, a call to unexpected() is made.
C++ Exception Handling
Overview
unexpected() and terminate() Functions
Using Exception Handling
Transferring Control
Example of Throwing an Unspecified
Exception
Syntax of an Exception Specification