Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throwing during unwinding -- why does this example work?

Consider this:

void thrower () {
    throw "123";
}

struct Catcher {
    ~ Catcher () {
        try {thrower ();}
        catch (...) {}
    }
};

int main () {
    try {
       Catcher c;
       throw 1.23;
    }
    catch (...) {}
}

This compiles and runs without calling terminate on gcc 4.3, but according to the standard (15.5.1)

...when the exception handling mechanism, after completing evaluation of the expression to be thrown but before the exception is caught (15.1), calls a user function that exits via an uncaught exception... terminate shall be called.

When ~Catcher is called after the double has been thrown, this is "after completing evaluation...before the exception is caught" and thrower is "a user function that exits via an uncaught exception", this satisfies the above condition. Yes, the char* is caught but only after the user function exits.

Shouldn't terminate have been called?

To emphasise this:

void do_throw () {
    throw "123";
}

void thrower () {
    do_throw ();
    // Uncaught exception here (A)
}

struct Catcher {
    ~ Catcher () {
        try {thrower (); /* (B) */}
        catch (...) {}
    }
};

int main () {
    try {
       Catcher c;
       throw 1.23;
    }
    catch (...) {}
}

(A) happens in the context of (B), which already has an exception in progress.

So, shouldn't terminate have been called? If not, and this is a legal situation in which we can have two simultaneous exceptions, where do we draw the line?

like image 841
spraff Avatar asked Dec 13 '22 09:12

spraff


1 Answers

Why should terminate have been called? You have a catch(...) block which catches all exceptions: one that catches the double (the one in main) and one that catches the char const[4] (the one in ~Catcher).

So no functions are "exiting with an uncaught exception" because all the exceptions are caught.

The key words here are "calls a user function which terminates with an uncaught exception". This is not the same as "calls a user function which somewhere down the line calls a user function which terminates with an uncaught exception." If you call a function and it has a try/catch block in it, and then in that you call some function which terminates with an exception but you catch the exception, terminate is not called.

tl;dr: The very first call in a call hierarchy originating between the exception evaluation and before the catch must exit with an exception for terminate to be called, not branches below the first call. This makes sense because there's no way you could set up another catch block between when the object being thrown was evaluated and when it was caught.

like image 94
Seth Carnegie Avatar answered Dec 14 '22 22:12

Seth Carnegie