为什么getA()
抛出的异常没有被捕获?
#include<iostream>
using namespace std;
class Base{
protected:
int a;
public:
Base() { a=34; }
Base(int i){ a = i; }
virtual ~Base() { if(a<0) throw a; }
virtual int getA()
{
if(a < 0) { throw a;}
}
};
int main()
{
try
{
Base b(-25);
cout << endl << b.getA();
}
catch (int) {
cout << endl << "Illegal initialization";
}
}
编辑:
我理解你所说的堆栈展开。
如果我将 Base
更改为以下内容,我现在可以打印“非法初始化”调试。为什么我不再收到对 terminate()
的调用?
Base() { a=34; }
Base(int i){ a = i; if(a<0) throw a;}
virtual ~Base() { if(a<0) throw a; }
virtual int getA()
{
return a;
}
最佳答案
调用 getA()
后,第一个异常被抛出,即所谓的 stack unwinding开始并且对象被销毁。当对象被销毁时,它的析构函数抛出另一个异常,该异常从析构函数的主体中逃脱并且(因为在堆栈展开期间发生)这导致 terminate()
立即被 C++ 运行时和 your program terminates 调用。 .
在您提交的第二个片段中,构造函数中抛出了异常,因此构造函数没有完成并且永远不会调用析构函数(因为析构函数仅针对完全构造的对象调用),因此 没有机会终止()
调用。
关于c++ - 未捕获的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4724660/