While reading "More Exceptional C++" by Hurb Sutter, i have stumbled upon the following code:
// Example 19-5: Alternative right solution
//
T::Close()
{
// ... code that could throw ...
}
T::~T() /* throw() */
{
try
{
Close();
}
catch( ... ) { }
}
My understanding was, this is not a good idea. Because, if T destructor is called during stack unwinding due to an exception, and then Close() throws an exception, then this will cause Terminate() to be called.
Can somebody shed some light on this. Thanks in advance.
My understanding was, this is not a good idea. Because, if T destructor is called during stack unwinding due to an exception, and then Close() throws an exception, then this will cause Terminate() to be called.
The try
-catch
block is there exactly to prevent that. The code:
try
{
Close();
}
catch( ... ) { }
will catch any exception thrown by Close
and ignore them. Therefore the destructor won't throw any exception, which could lead to the termination function being called.
It doesn't matter if Close
can throw unless the catch
lets the exception escape.
Typically the catch
clause is designed to never throw.
In fact not having the catch
clause would introduce the problem you are describing.
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