Stack unwinding in C++
In this tutorial, we will learn about stack unwinding in C++. Stack Unwinding is the removal of the function call stack items at runtime. In C++, the function call stack is searched for the exception handler whenever an exception occurs and all the items are removed from the function call stack before the function with the exception handler.
C++ Program to understand Stack Unwinding
#include<iostream> using namespace std; // function a() throws an int exception void a() throw (int) { cout<<"\n a() start"; throw 100; cout<<"\n a() end"; } // function b() that calls a() void b() throw(int) { cout<<"\n b() start"; a(); cout<<"\n b() end"; } // function c() that calls both a() and b() void c() { cout<<"\n c() start"; try { b(); } catch(int i) { cout<<"\n Caught Exception: "<<i; } cout<<"\n c() end"; } int main() { c(); }
Output:
c() start b() start a() start Caught Exception: 100 c() end
In the above program, the first function a()
throws an exception and since the function, a()
doesn’t have an exception handler, so its entry will be removed from the function call stack and then it goes to the b()
function and since b()
also doesn’t have an exception handler, it passes to the next entry which is c()
. Now the function c()
has the exception handler inside it and when the catch block inside c()
is executed, then the program is also executed. Therefore, b()
end and a()
end lines will also not be executed.
In the stack unwinding process, destructors for any local class objects inside a()
or b()
function would have been called.
Leave a Reply