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:
You can replace the default value of unexpected_handler with the function set_unexpected().
#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_unexpectedThe 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.