scope + destructor with Exception parameter for RAII

Sean Kelly sean at f4.ca
Tue Nov 28 15:10:59 PST 2006


One more follow-up and I promise I'll stop :-)  I just remembered why I 
changed Ares in the first place.  Since objects are finalized during GC 
collections, throwing from a dtor results in completely unpredictable 
program behavior.  For example:

     {
         class MyClass
         {
             ~this()
             {
                 throw new Exception( "die" );
             }
         }
         MyClass c = new MyClass();
     }

     OtherClass c = new OtherClass(); // A

In the program above, an exception may be thrown from point A that has 
*nothing to do with an out of memory condition* and worse, it will be 
thrown only if program memory is in a state where the GC needs to 
collect to free up resources.  It's even possible that the instance of 
MyClass could have been declared and allocated in a completely different 
thread, resulting it its being passed up a call stack that was not 
written to expect such a condition.  So the presence of a GC and 
GC-called finalizers makes throwing from dtors even worse than it is in 
deterministic situations (which is still quite bad).

Also, I have found few instances where an exception really needs to be 
thrown from a dtor.  While resource cleanup operations may indeed fail, 
more often than not the documentation will say that a failure may only 
occur if the parameters are invalid.  And with proper encapsulation is 
is guaranteed not to happen.


Sean



More information about the Digitalmars-d mailing list