注意:我在 redhat linux 6.3 上使用 gcc 4.4.7。下面示例中的问题是关于 GCC 对第一个抛出的异常做了什么,A::doSomething()
而不是关于是否应该从析构函数中抛出异常。
在以下代码中,函数以 2 个异常A::doSomething()
退出。析构函数中logic_error
的第二个似乎覆盖了from 。该程序的输出如下所示。logic_error
~A()
logic_error
A::doSomething()
我的问题logic_error
是A::doSomething()
. 有没有办法恢复它?
#include <iostream>
#include <stdexcept>
#include <sstream>
using namespace std;
class A
{
public:
A(int i):x(i) {};
void doSomething();
~A() {
cout << "Destroying " << x << endl;
stringstream sstr;
sstr << "logic error from destructor of " << x << " ";
throw logic_error(sstr.str());
}
private:
int x;
};
void A::doSomething()
{
A(2);
throw logic_error("from doSomething");
}
int main()
{
A a(1);
try
{
a.doSomething();
}
catch(logic_error & e)
{
cout << e.what() << endl;
}
return 0;
}
输出是:
Destroying 2
logic error from destructor of 2
Destroying 1
terminate called after throwing an instance of 'std::logic_error'
what(): logic error from destructor of 1
Aborted (core dumped)