Why doesn’t this piece of code run without error? Isn’t bad_exception supposed to be called automatically when an unexpected exception is encountered? Or is it necessary to set a handler for it?
#include <iostream>
#include <exception>
using namespace std;
class C{};
void test() throw(bad_exception)
{
throw C();
}
int main()
{
try
{
test();
} catch(bad_exception& e)
{
cout << "Caught ";
}
}
In C++03 theory:
If you throw an exception that is not in the exception specification,
unexpected()gets called. If you have not set the unexpected handler viaset_unexpected()this meansterminate()gets called which is the case you observed. If you have set an unexpected handler that does not call terminate but throws an exception, and if that exception is not listed in your exception specification, it gets translated into bad_exception. So in order to get the expected result, callset_unexpected()first with an appropriate handler.In C++03 practice:
Some compilers do not support exception specifications at all (other than
throw()), others just don’t evaluate/check them for correctness. As Herb Sutter points out, exception specifications create a clumsy “shadow type system” that is not easy to handle right (if it is possible at all). Therefore..… in C++11:
Exception specifications are deprecated. You should rather not use them. However, there is a
nothrowoperator that has a slightly different functionality thanthrow()PS: so why have std::bad_exception in C++03?
You hav three different regions of code:
So if the “foreign” code throws an exception that violates your exception specification, you have three possible outcomes of that:
Setting your own handler inside the function disables any handler that was previously set by anyone else who just wants to use your function. He will not expect you to disable his handler. Besides, the handler is meant as a global what-happens-if policy and thus is nothing you should care about in a single function implementation.