Topic: exceptions and destructors


Author: gregw@minotaur.tansu.com.au (Greg Wilkins)
Date: 28 Apr 1993 01:23:08 GMT
Raw View
Are destructors allowed to throw exceptions?   If so in the code:

    Foo *f= new Foo;
    try
    {
         delete f;
    }
    catch(...)
    {
         ???
    }

What is the state of *f in the handler?
Have the destructors for all sub-objects been called?
What is the best action that the handler can perform?
Should it be:

    Foo *f= new Foo;
    try
    {
         delete f;
    }
    catch(...)
    {
         void* v = (void*)f;
         delete v;
    }


-gregw






Author: fjh@munta.cs.mu.OZ.AU (Fergus James HENDERSON)
Date: Wed, 28 Apr 1993 09:12:54 GMT
Raw View
gregw@minotaur.tansu.com.au (Greg Wilkins) writes:

>Are destructors allowed to throw exceptions?

Yes.
However, if a destructor which is being executed as part of the stack
unwinding after an exception throws another exception, then the
exception handling mechanism gives up and calls a function (unexpected()?)
whose default behaviour is to call abort(). So really destructors
should never throw exceptions.

>If so in the code:
>
>    Foo *f= new Foo;
>    try
>    {
>         delete f;
>    }
>    catch(...)
>    {
>         ???
>    }
>
>What is the state of *f in the handler?

Could be anything from completely undestructed through partially
destructed through completely destructed but not deallocated.
Could even be garbage due to prior heap corruption.

>Have the destructors for all sub-objects been called?

Maybe, maybe not. It depends exactly where the exception was throw from.

>What is the best action that the handler can perform?

Probably the best thing is for the destructor to catch exceptions itself.
Then if the handler here gets executed, it knows that operator delete() must
have failed, which means that f is invalid or the heap is corrupted.
In either case attempting to call operator delete() again is not
going to be useful. The best thing to do would be to restart the program,
if possible; if not possible, then maybe just ignore it, muddle on, and
hope for the best. In any case, it makes sense to let the let the
exception propagate back some sort of top-level state before catching it,
though, rather than catching it here.

--
Fergus Henderson             fjh@munta.cs.mu.OZ.AU
This .signature virus is a self-referential statement that is true - but
you will only be able to consistently believe it if you copy it to your own
.signature file!