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?
"When an exception is thrown, the exception object is created and an placed generally on some sort of exception data stack" (Stanley Lippman, "Inside the C++ Object Model" - 7.2 Exception handling)
In the C++ exception mechanism, control moves from the throw statement to the first catch statement that can handle the thrown type. When the catch statement is reached, all of the automatic variables that are in scope between the throw and catch statements are destroyed in a process that is known as stack unwinding.
A stack overflow means, as you might expect, that you exceeded the memory given to the stack. Since the stack is typically allocated its own pages, going outside the stack walks outside a valid mapped memory address.
The exception object is copied to a special location to survive the stack unwinding. The reason you see two destructions is because when you exit f() the original exception is destroyed and when you exit g() the copy is destroyed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With