Destructors and exceptions

Duncan Booth me at
Tue Jun 8 13:22:07 CEST 2004

nicksjacobson at (Nick Jacobson) wrote in 
news:f8097096.0406080308.6df86699 at

> You know, I noticed this in the Python Reference Manual, p. 13, and
> have been wondering about it.
> "...note that catching an exception with a 'try...except' statement
> may keep objects alive..."
> No explanation is given, and I don't know why that's the case either. 
> But at least they're aware of it...HTH

When an exception is handled, you can access the stack traceback. This 
contains references to all the local variables which were in scope at the 
point when the exception was thrown. Normally these variables would be 
destroyed when the functions return, but if there is a traceback 
referencing them they stay alive as long as the traceback is accessible 
which is usually until the next exception is thrown.

If you really want to be sure your objects are destroyed, then use 'del' in 
the finally suite of a try..finally. This ensures that the traceback can't 
be used to reference the objects that you deleted.

More information about the Python-list mailing list