The unexpected() function (C++ only)

When a function with an exception specification throws an exception that is not listed in its exception specification, the C++ run time does the following:

  1. The unexpected() function is called.
  2. The unexpected() function calls the function pointed to by unexpected_handler. By default, unexpected_handler points to the function terminate().

You can replace the default value of unexpected_handler with the function set_unexpected().

Although unexpected() cannot return, it may throw (or rethrow) an exception. Suppose the exception specification of a function f() has been violated. If unexpected() throws an exception allowed by the exception specification of f(), then the C++ run time will search for another handler at the call of f(). The following example demonstrates this:

#include <iostream>
using namespace std;

struct E {
  const char* message;
  E(const char* arg) : message(arg) { }
};

void my_unexpected() {
  cout << "Call to my_unexpected" << endl;
  throw E("Exception thrown from my_unexpected");
}

void f() throw(E) {
  cout << "In function f(), throw const char* object" << endl;
  throw("Exception, type const char*, thrown from f()");
}

int main() {
  set_unexpected(my_unexpected);
  try {
    f();
  }
  catch (E& e) {
    cout << "Exception in main(): " << e.message << endl;
  }
}

The following is the output of the above example:

In function f(), throw const char* object
Call to my_unexpected
Exception in main(): Exception thrown from my_unexpected

The main() function's try block calls function f(). Function f() throws an object of type const char*. However the exception specification of f() allows only objects of type E to be thrown. The function unexpected() is called. The function unexpected() calls my_unexpected(). The function my_unexpected() throws an object of type E. Since unexpected() throws an object allowed by the exception specification of f(), the handler in the main() function may handle the exception.

If unexpected() did not throw (or rethrow) an object allowed by the exception specification of f(), then the C++ run time does one of two things:

Related information