So far I never had a single warning emitted by a C++ compilers but now VS 2015 compiler seems to suddenly start complaining about this.
It seems that C++11 implicitly mark every destructor as nothrow https://msdn.microsoft.com/query/dev14.query?appId=Dev14IDEF1&l=EN-US&k=k(C4297)&rd=true
Why is that? It may be a bad idea, but I would like to understand why? And if it's not inherently bad, is there a way to override it so that destructor is not a nothrow?
P.S. I know that exceptions may be evil, but sometimes they are usefull, especially when generating crash reports from users of my app.
Destructors are called when scopes are exited. When an exception is thrown, the stack is unwound which causes scopes to be exited and destructors to be called. When an exception is thrown while another is in progress, the process is unconditionally aborted with std::terminate. That is why throwing from destructors is a bad idea and why destructors are implicitly marked noexcept
(==noexcept(true)
)*.
If you want to throw from a destructor anyway, you can explicitly mark it noexcept(false) to override the default.
*If you throw from a function marked noexcept
, std::terminate
is called immediately
Why is that? It may be a bad idea, but I would like to understand why? And if it's not inherently bad, is there a way to override it so that destructor is not a nothrow?
Throwing exceptions in a destructor is a bad idea. The reason being during an exception stack unwinding happens i.e. destructor for all the objects on the stack is called. Now, as the stack unwinding was happening as a part of the exception, the destructor throws an exception again. You can end up having multiple exceptions and then there is no un-ambiguous way of handling these multiple exceptions. E.g. if there are two exceptions and I have a catch block for one exception and not other, shall my process terminate or the exception caught and processed further?
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