简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM