Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throwing an exception while handling an exception

I'm reading the "C++ Programming Language 4th edition" book and have a question regarding a paragraph about exception handling:

There are cases where exception handling must be abandoned for less subtle error-handling techniques. The guiding principles are:

  • Don't throw an exception while handling an exception.
  • Don't throw an exception that can't be caught.

If the exception-handling implementation catches you doing either, it will terminate your program.

Could someone give me an example of the first situtation? Only something like this comes to my mind but it's a valid code according to g++:

try
{
    throw 1;
}
catch(...)
{
    try
    {
        throw 2;
    }
    catch(...)
    {
        cout << "OK";
    }
}
like image 296
Quentin Avatar asked Jul 24 '13 15:07

Quentin


1 Answers

That's a bit misleading; it's fine to throw from an exception handler (which is what I'd understand by "while handling an exception"), as long as there's another handler to catch it.

The problem is if you throw an exception from the destructor of an object that's being destroyed during stack unwinding. In that case, there are two unhandled exceptions, and the usual exception mechanism can only deal with one; so the response is to call terminate.

Example:

struct dodgy {~dodgy() {throw "Don't do this!";}};

try {
    dodgy d;
    throw 1;
} catch (...) {
    // Never reached: destroying `d` killed the program.
}
like image 164
Mike Seymour Avatar answered Sep 28 '22 18:09

Mike Seymour