简体   繁体   中英

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." It crashes in release mode too. I understand that this because throw does not find the exact catch handler and std::terminate() is called. But, I had the understanding that catch(...) should handle this. Can someone let me know the exact handler that I need to use with 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(); catches the exception and the code crashes no longer, but I need to understand what happens with just calling throw from function/constructor?

Thanks.

You're not throwing an exception. You're just writing throw , which re-throws an exception already thrown. 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");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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