Throwing an exception while handling an exception

I am reading the book of the fourth edition of the C ++ Programming Language and ask a question regarding the paragraph on exception handling:

There are cases where exception handling should be discarded for less subtle error handling methods. Guidelines:

  • Do not handle the exception when handling the exception.
  • Do not throw an exception that cannot be caught.

If the implementation of exception handling forces you to do this, terminate your program.

Can someone give me an example of the first situation? Just something like this comes to my mind, but this is valid code according to g ++:

try { throw 1; } catch(...) { try { throw 2; } catch(...) { cout << "OK"; } } 
+7
c ++ exception-handling try-catch
source share
1 answer

This is a bit misleading; it's fine to throw an exception handler (which I would understand "when handling an exception") if there is another handler to catch it.

The problem is that you selected an exception from the destructor of the object, which is destroyed during the unwinding of the stack. In this case, there are two unhandled exceptions, and the usual exception mechanism can deal with only one; therefore, the answer should call terminate .

Example:

 struct dodgy {~dodgy() {throw "Don't do this!";}}; try { dodgy d; throw 1; } catch (...) { // Never reached: destroying `d` killed the program. } 
+12
source share

All Articles