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 dispatcher" 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.
The throw keyword allows the programmer to define custom exceptions. Exception handlers in C++ are declared with the catch keyword, which is placed immediately after the try block. Multiple handlers ( catch expressions) can be chained - each one with a different exception type.
The throw statement requires a single argument: a throwable object. Throwable objects are instances of any subclass of the Throwable class. Here's an example of a throw statement.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With