Handling an Exception

In previous issues we discussed throwing of exceptions and stack unwinding. Let’s now look at actual handling of an exception that has been thrown. An exception is handled via an exception handler. For example:

handles exceptions of type T. More precisely, a handler of the form:




will catch a thrown exception of type E, given that:

As an example of these rules, in the following case the thrown exception will be caught:

because A is a public base class of B. Handlers are tried in order of appearance. If, for example, you place a handler for a derived class after a handler for a corresponding base class, it will never be invoked. If we had a handler for B after A, in the example above, it would not be called. A handler like:

appearing as the last handler in a series, will match any exception type.

If no handler is found, the search for a matching handler continues in a dynamically surrounding try block. If no handler is found at all, a special library function terminate() is called, typically ending the program.

An exception is considered caught by a handler when the parameters to the handler have been initialized, and considered finished when the handler exits.

In the next issue we’ll talk a bit about exception specifications, that are used to specify what exception types a function may throw.