Destructors and exceptions

Konstantin Veretennicov kveretennicov at yahoo.com
Wed Jun 9 07:11:49 EDT 2004


dkturner at telkomsa.net (David Turner) wrote in message news:<e251b7ba.0406070651.1c98c09d at posting.google.com>...
> Hi all
> 
> I noticed something interesting while testing some RAII concepts
> ported from C++ in Python.

AFAIK, cpp-style RAII is mostly unportable to other languages.

> I haven't managed to find any information
> about it on the web, hence this post.

This discussion may be helpful:
http://mail.python.org/pipermail/python-list/2002-March/090979.html

> 
> The problem is that when an exception is raised, the destruction of
> locals appears to be deferred to program exit.  Am I missing
> something?  Is this behaviour by design?  If so, is there any reason
> for it?  The only rationale I can think of is to speed up exception
> handling; but as this approach breaks many safe programming idioms, I
> see it as a poor trade.
> 

My impression is that many (or all?) languages with GC (especially
non-refcounting) don't guarantee deterministic destruction of objects.
I guess it's hard to have both GC and DD :) Please correct me if I am wrong.

See also "Deterministic Destruction can be a Bug" for an example when DD
can be a bad thing:
http://www.hpl.hp.com/personal/Hans_Boehm/gc/det_destr.html

All that said, GC-enabled language still can provide some support for RAII
pattern. Consider this C# example:

using (Font f1 = new Font("Arial", 10), f2 = new Font("Arial", 12)) {
    // use f1 and f2...
} // compiler will call Dispose on f1 and f2 either on exit or on exception;
  // not sure about order of disposal, but you can nest "using" anyway

This saves you from trouble of coding try+finally+Dispose.
BTW, does anybody know whether MS borrowed or invented this construct?

- kv



More information about the Python-list mailing list