当从构造函数抛出异常时,应用程序崩溃

Application crashes when exception is thrown from constructor

本文关键字:应用程序 崩溃 抛出异常 构造函数      更新时间:2023-10-16

当从类构造函数抛出异常时,程序崩溃。在调试模式下运行时,我得到以下错误"VirtualCtor.exe中0x74A2DB18的未处理异常:Microsoft c++异常:[rethrow]在内存位置0x00000000。"它在发布模式下也会崩溃。我理解这是因为throw没有找到确切的catch处理程序,并且调用了std::terminate()。但是,我的理解是,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;
 }

修改代码throw bad_alloc();捕获异常和代码崩溃不再,但我需要了解发生了什么只是从函数/构造函数调用抛出?

谢谢。

没有抛出异常。您只是在编写throw,它重新抛出已经抛出的异常。在本例中,没有定义,因此程序具有未定义行为。所以才会出现崩盘。

如果你想扔东西,你就得扔东西!

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