What to do if a failed destructor cannot throw an exception

I noticed that you cannot throw an exception in the destructor. So my question is what to do if the destructor fails.

Another question: in what situation can the destructor fail?

Many thanks

+5
source share
5 answers

Ignore the error.

The destructor may “fail” if, for example, the class wraps some kind of output, and the destructor resets and closes this output. Data recording may fail. Then your parameters should interrupt the program, or catch an exception, ignore the error and return. Usually the right design should ignore it.

"close_and_flush", , , . , , , .

:

{
    OutputObject OO;
    write some stuff to OO, might throw;
    do more things, might throw;
    try {
        OO.flush_and_close();
    } catch (OutputException &e) {
        log what went wrong;
        maybe rethrow;
    }
}

:

try {
    OutputObject OO;
    write some stuff to OO, might throw;
    do more things, might throw;
    OO.flush_and_close();
} catch (AnyOldException &e) {
    log what went wrong;
    maybe rethrow;
}

, , , - , . , , - , .

+14

, . - ' , ( , , ).

+7

, " , " - , . , fclose() . , ? , :

  • . , , , .

  • . , , .

, ! , . , . - : " ( ), ?" - C, ++,

+6

, . , . "".

+3

!

RAII , RAII .

++. , , .

!!!!

, , :

class MyObject
{
    public :
       // etc.
       ~MyObject()
       {
          try
          {
             this->dispose() ;
          }
          catch(...) { /* log the problem, or whatever, but DON'T THROW */ }
       }

       void dispose()
       {
          if(this->isAlreadyDisposed == false)
          {
             this->isAlreadyDisposed = true ;

             // dispose the acquired resource          
          }
       }
} ;

, RAII. , , dispose .

dispose , (, , , , " " ..).

?

, , .

, .

, , , , ++. - , , , , .

, . - :

class MyObject
{
    bool & isOk ;

    public :
       // etc.
       MyObject(bool & p_isOk) : isOk(p_isOk) {}

       ~MyObject()
       {
          // dispose of the ressource
          // If failure, set isOk to false ;
       }
} ;

:

void foo()
{
   bool isOk = true ;

   // etc.

   {
      MyObject o(isOk) ;
      // etc.
   }


   if(isOk == false)
   {
      // Oops...
   }
}

. , , , ( , ...).

+2

All Articles