Terminate() And Unexpected()

Suppose that you have a bit of exception handling usage, like this:

What will happen? An exception of type “int” is thrown, but there is no handler for it. In this case, a special function terminate() is called. terminate() is called whenever the exception handling mechanism cannot find a handler for a thrown exception. terminate() is also called in a couple of odd cases, for example when an exception occurs in the middle of throwing another exception.

terminate() is a library function which by default aborts the program. You can override terminate if you want:

Note that this area is in a state of flux as far as compiler adaptation of new features. For example, terminate() should really be “std::terminate()”, and the declarations may be found in a header file “”. But not all compilers have this yet, and these examples are written using an older no-longer-standard convention.

In a similar way, a call to the unexpected() function can be triggered by saying:

unexpected() is called when a function with an exception specification throws an exception of a type not listed in the exception specification for the function. In this example, f()’s exception specification is:

A function declaration without such a specification may throw any type of exception, and one with:

is not allowed to throw exceptions at all. By default unexpected() calls terminate(), but in certain cases where the user has defined their own version of unexpected(), execution can continue.

There is also a brand-new library function:

that is true from the time after completion of the evaluation of the object to be thrown until completion of the initialization of the exception declaration in the matching handler. For example, this would be true during stack unwinding (see newsletter #017). If this function returns true, then you don’t want to throw an exception, because doing so would cause terminate() to be called.

Share
Tweet
Share
Pin