
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Stack Unwinding in C++
When we call some functions, the call stack stores the address, and after returning, it pops the address to resume work.
What is Stack Unwinding
Stack unwinding refers to the process of removing function call frames from the function call stack during runtime, wherein local objects are destroyed in the reverse order of their construction.
Why Stack Unwinding Occurs?
Stack unwinding occurs when an exception occurs in a function and is not handled immediately in that function. The program control goes back through each function step by step, cleaning up any temporary resources used by each function.
How Unwinding Works?
C++ looks for a way to handle the exception by searching for a "catch" block that can work with it. If a "catch" block is found in a higher function, it tries to handle the exception there. If no solution is found by the time it reaches the start, the program stops because it does not know what else to do.
So, after stack unwinding, once the stack is unwound to the function, the execution jumps to the catch block, where the exception is handled.
It is an important part of the C++ exception handling; it allows the programme to recover from the exception situations and continue execution from the safe point.
Implementation of Stack Unwinding
In the following example, we create a C++ program that implements the working of stack Unwinding.
#include <iostream> using namespace std; void function1() { cout << "\n Entering into function 1"; throw 100; // Exception thrown } void function2() { cout << "\n Entering into function 2"; function1(); } // Function to call function2 and handle the exception void function3() { cout << "\n Entering function 3 "; try { // Try to execute function 2 function2(); } catch (int i) { cout << "\n Caught Exception: " << i; } cout << "\n Exiting function 3"; } int main() { function3(); return 0; }
Following is the output:
Entering function 3 Entering into function 2 Entering into function 1 Caught Exception: 100 Exiting function 3
Here we can see that the control stores info of function 3, then enters into function 2, and then into function 1. After that one exception occurs, it removes all of the information from the stack and returns back to function 3 again.