0

I have a simple class as follow in test.h

class test
{
        test()
        {
            std::cout<<"constructor called"<<std::endl;
        }
        static test m_test;
        ~test()
        {
            std::cout<<"I am here"<<std::endl;
        }

};

and the static member is defined in test.cpp as:

test test::m_test;

The main has nothing :

main()
{

}

and I can see in the output:

constructor called
I am here

which is good. Now I am adding a bit of code that generate an exception like this:

 main()
 {
     for(int i=-1; i<1; i++)
     {
         i=1/i;   // this line generate an exception and close the application.
     }
}

In this case the destructor is not called. and I can only see that the constructor is called.

Why this is happening?

How can I make sure that if an expectation thrown and application crashed, the destructor is called? Assuming that I can only change my test class and not the main application.

mans
  • 17,104
  • 45
  • 172
  • 321

1 Answers1

1

Divide by zero is not an exception! It is not possible to catch it as it is a hardware signal to the operating system to interrupt your program.

Read more here:

C++ : Catch a divide by zero error

In order to throw a random exception you can just do

throw std::runtime_error("Oh no!");

but make sure you catch the thrown exception in the calling code with:

try {
   codeThatThrowsException();
} catch(const std::runtime_error& e) {
   std::cout << "An exception was thrown: " << e.what() << std::endl;
}
Community
  • 1
  • 1
Salgar
  • 7,687
  • 1
  • 25
  • 39