How are exceptions allocated on the stack caught beyond their scope?
- by John Doe
In the following code, the stack-based variable 'ex' is thrown and caught in a function beyond the scope in which ex was declared. This seems a bit strange to me, since (AFAIK) stack-based variables cannot be used outside the scope in which they were declared (the stack is unwound).
void f() {
SomeKindOfException ex(...);
throw ex;
}
void g() {
try {
f();
} catch (SomeKindOfException& ex) {
//Handling code...
}
}
I've added a print statement to SomeKindOfException's destructor and it shows that ex is destructed once it goes out of scope in f() but then it's caught in g() and destructed again once it goes out of scope there as well.
Any help?