I came upon an interesting scenario with flow control while working on my language. What happens if an exception is thrown while processing a break
statement. GCC seems to believe the break flow is lost, but the standard seems somewhat silent on what should happen.
For example, what should the following program actually do?
#include <iostream>
using namespace std;
struct maybe_fail {
bool fail;
~maybe_fail() {
if( fail )
throw 1;
}
};
int main() {
for( int i=0; i < 6; ++i ) {
cout << "Loop: " << i << endl;
try {
maybe_fail mf;
mf.fail = i % 2;
if( i == 3 )
break;
} catch( int ) {
cout << "Caught" << endl;
}
}
return 0;
}
Note that a return
will also be blocked, as will a continue
(add output after the catch to see that). Attempt to goto
outside of the block will also be caught.
What is the correct flow? The standard doesn't seem to address this: section 6.6 on jump statements makes no mention, neither does section 15 on exception handling. I do understand that exceptions in destructors is in terribly bad form, but if you are using something like BOOST_SCOPE_EXIT for defer statements this behaviour might become quite important.
Perhaps of interest, the same flow happens in Java and Python, so at least there seems to be some consistency in the imperative languages.
terminate()
is called if you're in a "double-exception-handling" situation, but your example seems to continue the advice that it's just bad to do so.break
statement and exit the loop (exiting the loop is what is intended when somebody writesbreak
so it makes an equal amount of sense, if not more)