I am trying to use the following code to test “set_unexpected()”. I expect the code will generate an output like:
In function f(), throw const char* object
Call to my_unexpected
Exception in main(): Exception thrown from my_unexpected
But I got a run-time error: “This application has requested the Runtime to terminate it in an unusual way.” So, what would be the problem? Thanks
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 _tmain(int argc, _TCHAR* argv[])
{
set_unexpected(my_unexpected);
try {
f();
}
catch (E& e) {
cout << "Exception in main(): " << e.message << endl;
}
return 0;
}
Visual C++ does not implement correctly exception specifications. As stated here,
and in particular
Also here:
Because of this, your
terminatehandler is never called, and since no handlers forconst char *are present in your code the exception is not caught and the application terminates abnormally.Anyway, keep in mind that exception specifications different from
throw()are generally considered a bad idea, and actually the new C++ standard (C++11) deprecates them, introducingnoexceptfor whatthrow()was used.