InterviewSolution
| 1. |
What do you mean by Stack unwinding? |
|
Answer» Stack Unwinding happens during exception handling. During an exception occurrence, the destructor is called to DESTROY all local objects for the place where the exception was thrown and where it was caught. An exception causes the CONTROL to pass on from a try block to the respective exception handler. The destructors for all constructed automatic objects are called at run time which where created since the beginning of the try block. The automatic objects are destroyed in reverse order of their construction. Note: The corresponding objects must be created before destruction of the same which takes place during Stack Unwinding. The terminate() function is invoked during Stack Unwinding on a destructor for a UNHANDLED exception. The following example demonstrates this: #include <iostream> using namespace std; STRUCT E { const char* message; E(const char* arg) : message(arg) { } }; void my_terminate() { cout << "Call to my_terminate" << endl; }; struct A { A() { cout << "In constructor of A" << endl; } ~A() { cout << "In destructor of A" << endl; throw E("Exception thrown in ~A()"); } }; struct B { B() { cout << "In constructor of B" << endl; } ~B() { cout << "In destructor of B" << endl; } }; int main() { set_terminate(my_terminate); try { cout << "In try block" << endl; A a; B b; throw("Exception thrown in try block of main()"); } catch (const char* e) { cout << "Exception: " << e << endl; } catch (...) { cout << "Some exception caught in main()" << endl; } cout << "Resume execution of main()" << endl; }The output of this example: In try block In constructor of A In constructor of B In destructor of B In destructor of A Call to my_terminateIn the try block, two automatic objects are created: a and b. The try block throws an exception of type const char*. The handler catch (const char* e) CATCHES this exception. The C++ run time unwinds the stack, calling the destructors for a and b in reverse order of their construction. The destructor for a throws an exception. Since there is no handler in the program that can handle this exception, the C++ run time calls terminate(). (The function terminate() calls the function specified as the argument to set_terminate(). In this example, terminate() has been specified to call my_terminate().) |
|