Try the catch block in the destructor

While reading Herb Sutter's More Exceptional C ++, I came across 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 the expansion of the stack due to an exception, and then Close () throws an exception, it will call the Terminate () call.

Can someone shed some light on this. Thanks in advance.

+4
source share
3 answers

My understanding was, this is not a good idea. Because, if T destructor is called during the expansion of the stack due to an exception, and then Close () throws an exception, it will call the Terminate () call.

Block try- catchdesigned to prevent this. The code:

try
{
    Close();
}
catch( ... ) { }

will catch any exception thrown Closeand ignore them. Therefore, the destructor will not throw any exception, which can lead to a call to the termination function.

+7
source

, Close , catch .

catch , .

, catch, , .

+6

An interesting article about catches in a destructor:

https://akrzemi1.wordpress.com/2011/09/21/destructors-that-throw/

0
source

Source: https://habr.com/ru/post/1598439/


All Articles