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.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With