开发者

What happens when an exception is thrown while unwinding the 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 &开发者_如何学Pythonlt;< 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?


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:

  • Why exactly is calling the destructor for the second time undefined behavior in C++?
  • throwing exceptions out of a destructor
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜