Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are exceptions allocated on the stack caught beyond their scope?

Tags:

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?

like image 754
John Doe Avatar asked Mar 08 '10 19:03

John Doe


People also ask

Where are exceptions allocated C++?

"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)

What is the role of stack in 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.

What happens when we allocate space in the stack?

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.


1 Answers

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.

like image 142
Anders Abel Avatar answered Nov 05 '22 10:11

Anders Abel