What happens when an exception occurs while unwinding a stack from another exception?

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 destructor throws an exception that causes the A destructor to unwind the stack, resulting in another exception. What will be the reaction of the program?

+4
source share
1 answer

Short answer? Bang, the completion of the application.

From parashift :

During packet unwinding, all local objects in all of these stack frames are destroyed. If one of these destructors throws an exception (say, it throws a Bar object), the C ++ runtime system is in a situation without a win: should I ignore the panel and end in

 } catch (Foo e) { 

where was he originally headed? If he ignores Foo and searches

 } catch (Bar e) { 

handler? There is no good answer - any choice loses information.

Thus, C ++ guarantees that at that moment it will call terminate() , and terminate() will kill the process. Kill, you're dead.

Related stack overflow questions:

+6
source

Source: https://habr.com/ru/post/1316666/


All Articles