For example in the following code:
#include <iostream>
using namespace std;
class A {
public:
A() { cout << "A::A()" << endl; }
~A() { cout << "A::~A()" << endl; throw "A::exception"; }
};
class B {
public:
B() { cout << "B::B()" << endl; throw "B::exception"; }
~B() { cout << "B::~B()"; }
};
int main(int, char**)
{
try {
cout << "Entering try...catch block" << endl;
A objectA;
B objectB;
cout << "Exiting try...catch block" << endl;
}
catch (char* ex) {
cout << ex << endl;
}
return 0;
}
B
's destructor throws an exception, which invokes A
's destructor while unwinding the stack, resulting in the throw of another exception.
What will be the program's reaction?
When an exception is thrown and control passes from a try block to a handler, the C++ run time calls destructors for all automatic objects constructed since the beginning of the try block. This process is called stack unwinding. The automatic objects are destroyed in reverse order of their construction.
When an exception is thrown, destructors of the objects (whose scope ends with the try block) are automatically called before the catch block gets executed. That is why the above program prints “Destructing an object of Test” before “Caught 10“.
After the formal parameter is initialized, the process of unwinding the stack begins. This involves the destruction of all automatic objects that were fully constructed—but not yet destructed—between the beginning of the try block that is associated with the catch handler and the throw site of the exception.
If a function throws an exception and that exception isn't caught in main program will crash badly.
Short answer? Bang, application termination.
From parashift:
During stack unwinding, all the local objects in all those stack frames are destructed. If one of those destructors throws an exception (say it throws a Bar object), the C++ runtime system is in a no-win situation: should it ignore the Bar and end up in the
} catch (Foo e) {
where it was originally headed? Should it ignore the Foo and look for a
} catch (Bar e) {
handler? There is no good answer — either choice loses information.
So the C++ language guarantees that it will call terminate()
at this point, and terminate()
kills the process. Bang you're dead.
Related questions on Stack Overflow:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With