The process of removing function entries from function call stack at run time is called Stack Unwinding. Stack Unwinding is generally related to Exception Handling. In C++, when an exception occurs, the function call stack is linearly searched for the exception handler, and all the entries before the function with exception handler are removed from the function call stack. So exception handling involves Stack Unwinding if exception is not handled in same function (where it is thrown).
For example, output of the following program is:
f3() Start f2() Start f1() Start Caught Exception: 100 f3() End
In the above program, when f1() throws exception, its entry is removed from the function call stack (because it f1() doesn’t contain exception handler for the thrown exception), then next entry in call stack is looked for exception handler. The next entry is f2(). Since f2() also doesn’t have handler, its entry is also removed from function call stack. The next entry in function call stack is f3(). Since f3() contains exception handler, the catch block inside f3() is executed, and finally the code after catch block is executed. Note that the following lines inside f1() and f2() are not executed at all.
On a side note, if there were some local class objects inside f1() and f2(), destructors for those local objects would have been called in Stack Unwinding process.
Stack Unwinding also happens in Java when exception is not handled in same function.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Stack in C++ STL
- stack swap() in C++ STL
- stack empty() and stack size() in C++ STL
- stack top() in C++ STL
- stack push() and pop() in C++ STL
- stack emplace() in C++ STL
- Heap overflow and Stack overflow
- Minimum cells to be flipped to get a 2*2 submatrix with equal elements
- Nested Loops in C++ with Examples
- _Find_first() function in C++ bitset with Examples
- _Find_next() function in C++ bitset with Examples
- Left-Right traversal of all the levels of N-ary tree
- Difference between Iterators and Pointers in C/C++ with Examples
- ostream::seekp(pos) method in C++ with Exmaples