#include <iostream>#include<cstdlib>using namespace std;class E { public: const char* error; E(const char* arg) : error(arg) { }};voID my_terminate() { cout << "Call to my_terminate" << endl;}struct A { A() { cout << "In constructor of A" << endl; } ~A(){ cout << "In destructor of A" << endl; throw E("Exception thrown in ~A()"); }};struct B { B() { cout << "In constructor of B" << endl; } ~B() { cout << "In destructor of B" << endl; }};int main() { set_terminate(my_terminate); try { cout << "In try block" << endl; A a; B b; throw E("Exception thrown in try block of main()"); // line 36 } catch (E& e) { cout << "Exception: " << e.error << endl; } catch (...) { cout << "Some exception caught in main()" << endl; } cout << "Resume execution of main()" << endl;}
输出:
In try blockIn constructor of AIn constructor of BIn destructor of BIn destructor of ACall to my_terminatedisallowed system call: SYS_kill
在第36行中,从main中的try块抛出异常.现在为什么这个异常没有被处理程序捕获?
相反,“堆栈展开”过程继续.A的析构函数也抛出一个异常,它再次没有被任何处理程序捕获,而是调用my_terminate,为什么?
为什么在这两种情况下不调用处理程序?
解决方法 The C++ rule is that you must never throw an exception from a destructor that is being called during the “stack unwinding” process of another exception.你在A的析构函数中抛出异常,这是你不应该做的事情.
总结以上是内存溢出为你收集整理的c – 异常处理中的混淆全部内容,希望文章能够帮你解决c – 异常处理中的混淆所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)