Hi I found this line in a tutorial on web.
What happens when you declare a static object and the destructor throws and exception?
As with static constructor exceptions the application will crash.
I can't seam to understand what's the difference if object is static or not...
Thanks
I'm not sure if you're asking about constructors or destructors that throw exceptions - the problem statement refers to destructors, but the example code and some of the comments refer to constructors.
With regards to constructors that throw, it depends on whether the static object is local or global. Local static objects are constructed the first time that control passes through the scope in which they are defined, and exception handlers should behave normally for them. Global static objects are constructed before the program enters main()
; since you can't have a try-catch block at global scope, if the constructor of a global static object throws, it basically means that your application crashes before it makes it out of the starting gate.
As for destructors, generally speaking, destructors that can throw exceptions create serious problems. Herb Sutter details the reasons why in his great book "Exceptional C++", which is available here on Google Books. Basically, if a destructor can throw exceptions, it makes it nearly impossible to write exception-safe code. Consider the following example.
class T
{
T() {}
~T() { throw 5; }
};
void foo()
{
T t;
throw 10;
}
When foo()
reaches the throw 10;
statement, control will exit the context of foo()
, destroying the local object t
in the process. This calls the destructor for t
, which tries to throw another exception. In C++, it isn't possible to throw two exceptions simultaneously; if a second exception is thrown like this, the program calls the built-in function terminate()
, which does what it sounds like and terminates the program (you can set your own function to be called instead using set_terminate
, but this is mostly for doing custom clean-up - you can't change the fact that the program ends after the function is done).
The way to avoid this is to make sure that destructors never throw exceptions. It may not matter with static objects, because as celtschk noted the destructor won't be called until the program is terminating anyway, but as a general rule, if you find yourself writing a class with a destructor that can throw an exception, you should think carefully about whether it is really the best approach.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With