Throwing an exception when throwing an exception

This code:

#include <iostream> #include <stdexcept> using namespace std; int throw_it() { throw range_error( "foo" ); } int main() { try { throw throw_it(); } catch ( exception const &e ) { cerr << e.what() << endl; return 0; } } 

prints foo at startup, but is it guaranteed? More specifically, does an exception throw an exception into a specific behavior when retrieving the result of an exception? And is this behavior a throw of the most recently thrown exception (as the above test code does)?

FYI:

 $ g++ --version i686-apple-darwin11-llvm-g++-4.2 (GCC) 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.11.00) 
+7
source share
2 answers

Only one exception can be evaluated at a time. From 15.1 / 7

If the mechanism for handling exceptions, after evaluating the expression being completed, but before the exception is caught, calls a function that leaves the exception, std :: terminate is called.

In your example, std::terminate() not called, because in fact only one exception is thrown. When throw throw_it(); reached throw throw_it(); , throw_it() is evaluated first, which causes the function to be called before the exception is actually thrown. Since the function throws an exception and never returns the original throw , it will never be reached. If throw_it() does not throw an exception and returns an integer value, then the throw expression will be executed. Therefore, for your example, foo guaranteed to be printed.

But what about throwing a new exception from the active handler? When an exception is caught, it has been fully evaluated. When you throw a new exception (instead of throwing it with a throw), the original exception is destroyed and the evaluation of the new exception begins.

From 15.1 / 4

The exception object is destroyed after the last remaining active handler for the exception exits by any means other than re-creating or ....

This satisfies the rule that only one exception can be evaluated at a time.

+14
source

In particular, does an exception in the process throw the result of the exception into a specific behavior?

this is normal if it is not after creating an exception object and before searching for it, because then std::terminate will be called. In your example, an exception object is not created at all, so you don’t need to throw anything, range_error("foo") is thrown instead. This is an exception.

You can check it as follows:

 int throw_it() { throw range_error( "foo" ); return 19; } int main() { try { try { // nested try is perfectly legal throw throw_it(); } catch (...) { cerr << "not good!"; } } catch (exception const &e) { cerr << e.what() << endl; return 0; } } 

exit:

 not good! RUN SUCCESSFUL (total time: 59ms) 
+3
source

All Articles