What does a single "throw;" statement do?

C++ExceptionThrow

C++ Problem Overview


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.

C++ Solutions


Solution 1 - C++

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

Solution 2 - C++

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

Solution 3 - C++

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionereOnView Question on Stackoverflow
Solution 1 - C++Alan StokesView Answer on Stackoverflow
Solution 2 - C++dalleView Answer on Stackoverflow
Solution 3 - C++sharptoothView Answer on Stackoverflow