Reputation: 27
Hi all I'm facing some difficulties understanding the following code which deals with handling uncaught exceptions and I have a few question regarding the example below.
1) Just wondering why the output is: "call to my unexpected" and "caught bad expression" and not "call to my unexpected", "Caught X"
2) what does throw(X,Y, bad_exception)
mean in 'void f()' function.
3) what does typedef void (*pfv)();
actually means
class X { };
class Y { };
class A { };
typedef void (*pfv)();
void my_terminate() {
cout << "Call to my_terminate" << endl;
abort();
}
void my_unexpected() {
cout << "Call to my_unexpected" << endl;
throw;
}
void f() throw(X,Y, bad_exception) {
throw A();
}
void g() throw(X,Y) {
throw A();
}
int main()
{
pfv old_term = set_terminate(my_terminate);
pfv old_unex = set_unexpected(my_unexpected);
try {
cout << "In first try block" << endl;
f();
}
catch(X) {
cout << "Caught X" << endl;
}
catch(Y) {
cout << "Caught Y" << endl;
}
catch (bad_exception& e1) {
cout << "Caught bad_exception" << endl;
}
catch (...) {
cout << "Caught some exception" << endl;
}
}
sorry for the multiple question being asked, hope someone is able to explain to me in layman terms. Thanks and appreciate..
Upvotes: 2
Views: 3735
Reputation: 20626
1) When you call f
, it throws an exception whose type (A
) is not part of its exception specification. This leads to the registered unexpected handler being called, which in this case is my_unexpected
. This prints "Call to my_unexpected" and then rethrows the original exception (which as noted had a type that was not part of f
's exception specification), which causes a bad_exception
to be thrown (but only because bad_exception
is part of the exception specification of f
). This is then caught in main
, and "Caught bad_exception" is printed.
2) It means "f
may throw an X
, a Y
or a bad_exception
, and if it tries to throw anything else then the unexpected handler will be called".
3) It means "pfv is the type of a pointer to a function taking no parameters and with void return type". Thus pfv old_term;
means that old_term
is such a function pointer.
This is a useful link, for what it's worth:
The particularly relevant bit is at the bottom, where it says (emphasis mine):
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:
- If the exception specification of f() included the class std::bad_exception, unexpected() will throw an object of type std::bad_exception, and the C++ run time will search for another handler at the call of f().
- If the exception specification of f() did not include the class std::bad_exception, the function terminate() is called.
Upvotes: 2