0

I am trying to call terminate function. [I think this function gets called when another exception arises during stack unwinding]. The same scenario I have written and trying to verify.

I am able to see a call being made to terminate() function but i am not sure why i am geting the Debug Error.

While trying to execute the following code in Visual studio 2008, I am getting an error message dialog box "Debug Error". The output is also being displayed:

Output:

In try block

In constructor of A

In constructor of B

In destructor of B

In destructor of A

Call to my_terminate

Why this "Debug Error" window appears while executing this code? It is expected behavior? How to remove this error?

class E
{
public:
      const char* message;
      E(const char* arg) : message(arg) { }
};
void my_terminate() 
{
      cout << "Call to my_terminate" << endl;
};

class A 
{
public:
      A() { cout << "In constructor of A" << endl; }
      ~A() 
      {
          cout << "In destructor of A" << endl;
          throw E("Exception thrown in ~A()");
      }
};

class B 
{
public:

         B() { cout << "In constructor of B" << endl; }
         ~B() { cout << "In destructor of B" << endl; }
};

void main() 
{
      set_terminate(my_terminate);

      try 
      {
        cout << "In try block" << endl;
        A a;
        B b;
        throw("Exception thrown in try block of main()");
      }
      catch (const char* e) 
      {
        cout << "Exception: " << e << endl;
      }
      catch (...)
      {
        cout << "Some exception caught in main()" << endl;
      }

      cout << "Resume execution of main()" << endl;
      getch();
}
4

1 回答 1

3

You are throwing exception from ~A(). Throwing an exception out of a destructor is dangerous. If another exception is already propagating the application will terminate. See https://stackoverflow.com/a/130123/72178 for more detailed description.

Why this "Debug Error" window appears while executing this code?

You are throwing exception in main from try block. This invokes "Stack unwinding" and destructors of A and B are called. When exception is thrown from ~A() application terminates.

It is expected behavior?

Yes, it is defined by Standard.

How to remove this error?

Don't throw from destructors.

于 2012-04-07T07:31:44.363 回答