What does a single "throw;" statement do?
These days, I have been reading a lot the C++ F.A.Q and especially this page.
Reading through the section I discovered a "technique" that the author calls "exception dispatc开发者_运维技巧her" that allows someone to group all his exception handling in one handy function:
void handleException()
{
try {
throw; // ?!
}
catch (MyException& e) {
//...code to handle MyException...
}
catch (YourException& e) {
//...code to handle YourException...
}
}
void f()
{
try {
//...something that might throw...
}
catch (...) {
handleException();
}
}
What bothers me is the single throw;
statement: if you consider the given example then sure, it is obvious what it does: it rethrows the exception first caught in f()
and deals with it again.
But what if I call handleException()
on its own, directly, without doing it from a catch()
clause ? Is there any specified behavior ?
Additionally for bonus points, is there any other "weird" (probably not the good word) use of throw
that you know of ?
Thank you.
If you do a throw;
on its own, and there isn't a current exception for it to rethrow, then the program ends abruptly. (More specifically, terminate()
is called.)
Note that throw; is the only safe way to re-throw the current exception - it's not equivalent to
catch (exception const & e) { throw e; }
Yes, it specified behavior, it will call terminate;
15.1, para 8: If no exception is presently being handled, executing a throw expression with no operand calls terminate() (15.5.1).
That's so-called exception handler. It rethrows the "current exception" if any. If there's no exception currently being handled terminate()
will be called.
精彩评论