Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Try Catch block in destructor

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.

like image 887
Sam Avatar asked Jul 17 '15 20:07

Sam


2 Answers

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.

like image 67
Shoe Avatar answered Oct 03 '22 06:10

Shoe


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.

like image 34
Guvante Avatar answered Oct 03 '22 05:10

Guvante