从其他线程中,我知道我们不应该在析构函数中抛出异常!但是对于下面的例子,它确实有效。这是否意味着我们只能在一个实例的析构函数中抛出异常?我们应该如何理解这个代码示例!
#include <iostream>
using namespace std;
class A {
public:
~A() {
try {
printf("exception in A start\n");
throw 30;
printf("exception in A end\n");
}catch(int e) {
printf("catch in A %d\n",e);
}
}
};
class B{
public:
~B() {
printf("exception in B start\n");
throw 20;
printf("exception in B end\n");
}
};
int main(void) {
try {
A a;
B b;
}catch(int e) {
printf("catch in main %d\n",e);
}
return 0;
}
输出结果为:
exception in B start
exception in A start
catch in A 30
catch in main 20
B b;
后面尝试插入throw 42;
。 - Fred Larsonterminate called after throwing an instance of 'int'
的错误提示。 - Fred Larson<iostream>
不是定义printf
的必需头文件,但可以使用它。 - Pete Becker