Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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.

like image 975
ereOn Avatar asked Mar 21 '11 14:03

ereOn


People also ask

What does C++ throw do?

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.

Which requires a single argument a throwable object?

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.


2 Answers

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; }

like image 147
Alan Stokes Avatar answered Oct 02 '22 15:10

Alan Stokes


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).

like image 23
dalle Avatar answered Oct 02 '22 17:10

dalle