简体   繁体   English

从构造函数引发异常时,应用程序崩溃

[英]Application crashes when exception is thrown from constructor

When an exception is thrown from the class constructor, the program crashes. 从类构造函数引发异常时,程序崩溃。 While running in debug mode I get the following error "Unhandled exception at 0x74A2DB18 in VirtualCtor.exe: Microsoft C++ exception: [rethrow] at memory location 0x00000000." 在调试模式下运行时,出现以下错误“ VirtualCtor.exe在0x74A2DB18处出现未处理的异常:Microsoft C ++异常:在内存位置0x00000000 [重新抛出]。” It crashes in release mode too. 它也会在发布模式下崩溃。 I understand that this because throw does not find the exact catch handler and std::terminate() is called. 我明白这是因为throw找不到确切的catch处理程序,并且调用了std :: terminate()。 But, I had the understanding that catch(...) should handle this. 但是,我的理解是catch(...)应该处理此问题。 Can someone let me know the exact handler that I need to use with 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;
 }

Changing code throw bad_alloc(); 更改代码将抛出bad_alloc(); catches the exception and the code crashes no longer, but I need to understand what happens with just calling throw from function/constructor? 捕获异常,代码不再崩溃,但我需要了解仅从函数/构造函数调用throw会发生什么情况?

Thanks. 谢谢。

You're not throwing an exception. 不会抛出异常。 You're just writing throw , which re-throws an exception already thrown. 您只是在编写throw ,它会重新抛出一个已经抛出的异常。 In this case, there isn't one, so your program has undefined behaviour. 在这种情况下,没有一个,因此您的程序具有未定义的行为。 Hence the crash. 因此崩溃。

If you want to throw something, you actually have to throw something! 如果要扔东西,实际上必须扔东西!

MyClass()
{
   cout << "Default Ctor" << endl;
   throw std::runtime_exception("Testing exception handling");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM