【发布时间】:2013-06-05 14:25:36
【问题描述】:
注意:我在 redhat linux 6.3 上使用 gcc 4.4.7。下面示例中的问题是关于 GCC 对从 A::doSomething() 抛出的第一个异常做了什么,而不是关于是否应该从析构函数中抛出异常。
在以下代码中,函数 A::doSomething() 退出时出现 2 个 logic_error 异常。
析构函数~A() 中的第二个logic_error 似乎覆盖了A::doSomething() 中的logic_error。
该程序的输出如下所示。
我的问题是A::doSomething() 抛出的logic_error 发生了什么。有办法恢复吗?
#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)
【问题讨论】:
-
请修正缩进。目前无法阅读。
标签: c++