C++ runtime destructs all automatic variables created between between throw & catch. In this simple example below f1() throws and main() catches, in between objects of type B and A are created on the stack in that order. When f1() throws, B and A's destructors are called.
#include <iostream>
using namespace std;
class A
{
public:
~A() { cout << "A's dtor" << endl; }
};
class B
{
public:
~B() { cout << "B's dtor" << endl; }
};
void f1()
{
B b;
throw (100);
}
void f()
{
A a;
f1();
}
int main()
{
try
{
f();
}
catch (int num)
{
cout << "Caught exception: " << num << endl;
}
return 0;
}
The output of this program will be
B's dtor
A's dtor
This is because the program's callstack when f1() throws looks like
f1()
f()
main()
So, when f1() is popped, automatic variable b gets destroyed, and then when f() is popped automatic variable a gets destroyed.
Hope this helps, happy coding!