Quentin
Quentin

Reputation: 1086

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

Upvotes: 10

Views: 4427

Answers (1)

Mike Seymour
Mike Seymour

Reputation: 254431

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

Upvotes: 16

Related Questions