c – 异常处理中的混淆
发布时间:2020-12-16 10:50:10 所属栏目:百科 来源:网络整理
导读:考虑以下程序 #include iostream#includecstdlibusing 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"
|
考虑以下程序
#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 block In constructor of A In constructor of B In destructor of B In destructor of A Call to my_terminate Disallowed 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的析构函数中抛出异常,这是你不应该做的事情. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
