[英]Application crashes when exception is thrown from constructor
从类构造函数引发异常时,程序崩溃。 在调试模式下运行时,出现以下错误“ VirtualCtor.exe在0x74A2DB18处出现未处理的异常:Microsoft C ++异常:在内存位置0x00000000 [重新抛出]。” 它也会在发布模式下崩溃。 我明白这是因为throw找不到确切的catch处理程序,并且调用了std :: terminate()。 但是,我的理解是catch(...)应该处理此问题。 有人可以让我知道需要与catch一起使用的确切处理程序吗?
#include<iostream>
#include<exception>
using namespace std;
class MyClass
{
public:
MyClass() { cout << "Default Ctor" << endl;
throw; //runtime exception.
}
~MyClass()
{
cout << "Destructor called" << endl;
}
};
int main()
{
MyClass*vpt = nullptr;
try {
vpt = new MyClass;
}
catch (...) {
delete vpt;
cout << "Exception"<< endl;
}
return 0;
}
更改代码将抛出bad_alloc(); 捕获异常,代码不再崩溃,但我需要了解仅从函数/构造函数调用throw会发生什么情况?
谢谢。
您不会抛出异常。 您只是在编写throw
,它会重新抛出一个已经抛出的异常。 在这种情况下,没有一个,因此您的程序具有未定义的行为。 因此崩溃。
如果要扔东西,实际上必须扔东西!
MyClass()
{
cout << "Default Ctor" << endl;
throw std::runtime_exception("Testing exception handling");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.