Throwing An Exception

In the last issue we introduced C++ exception handling. In this issue we’ll go more into detail about throwing exceptions.

Throwing an exception transfers control to an exception handler. For example:

In this example the exception with value 37 is thrown, and control passes to the handler. A throw transfers control to the nearest handler with the appropriate type. “Nearest” means in the sense of stack frames and try blocks that have been dynamically entered.

Typically an exception that is thrown is of class type rather than a simple constant like “37”. Throwing a class object instance allows for more sophisticated usage such as conveying additional information about the nature of an exception.

A class object instance that is thrown is treated similarly to a function argument or operand in a return statement. A temporary copy of the instance may be made at the throw point, just as temporaries are sometimes used with function argument passing. A copy constructor if any is used to initialize the temporary, with the class’s destructor used to destruct the temporary. The temporary persists as long as there is a handler being executed for the given exception. As in other parts of the C++ language, some compilers may be able in some cases to eliminate the temporary.

An example:

If you run this program, you can trace through the various stages of throwing the exception, including the actual throw, making a temporary copy of the class instance, and the invocation of the destructor on the temporary.

It’s also possible to have “throw” with no argument, as in:

What does this mean? Such usage rethrows the exception, using the already-established temporary. The exception thrown is the most recently caught one not yet finished. A caught exception is one where the parameter of the catch clause has been initialized, and for which the catch clause has not yet been exited.

So in the example above, “throw;” would rethrow the exception represented by “e”. Because there is no outer catch clause to catch the rethrown exception, a special library function terminate() is called. If an exception is rethrown, and there is no exception currently being handled, terminate() is called as well.

In the next issue we’ll talk more about how exceptions are handled in a catch clause.