TITLE: exceptions in destructors (Newsgroups: comp.std.c++, 6 Oct 97) BOWMAN: "Kevin J. Bowman" |> For some time I have been designing classes that throw |> exceptions from a constructor. This helps to catch |> problems with the allocation of resources. Recently |> I have been working on a class which needs to make |> sure that a system resource has been restored to a |> previous state when the object (that changed the |> resource on creation) is destroyed. If, for some |> reason, the resource could not be restored to its |> previous state, I throw an exception. However, I |> see a potential problem with this: if the destructor |> throws an exception, the destructor does not complete |> and the object is not destroyed (unless I attempt to |> fix the problem and try to destroy it again in the |> future). This could lead to a memory leak. |> |> I know it's *legal* to throw an exception from a |> destructor but my question is: is it acceptable to |> throw an exception from a destructor or not? |> I'd like to hear comments pro and con. KANZE: kanze@gabi-soft.fr (J. Kanze) The general concensus is that it is a bad idea. C++ doesn't support nested exceptions. If the destructor exits because of an exception during stack walkback due to another exception being thrown, terminate will be called. And if you're using exceptions, it is difficult to prevent this case. In general, if something can fail, it should be in an explicitly called function, rather than the destructor, so that the object is still around after the operation so that the operation can, eventually, be retried. On the other hand, this specific issues you are worried about shouldn't cause a problem if the object is correctly designed -- if a destructor throws an exception, further execution of that destructor doesn't take place, but if memory serves me right, all sub-objects whose destructor has not yet been entered will be destructed. (The wording in the last public draft was not clear that this was the case; I believe that this has since been made clear. I don't think I'd count on current compilers to implement it according to a draft that hasn't yet been made public, however. I'd verify, but I'm having trouble connecting to the working group's site.)