File not closed on exception
eckhardt at satorlaser.com
Tue Oct 20 13:26:03 CEST 2009
arve.knudsen at gmail.com wrote:
> On Oct 19, 3:48 pm, Ethan Furman <et... at stoneleaf.us> wrote:
>> arve.knud... at gmail.com wrote:
>>> def create():
>>> f = file("tmp", "w")
>>> raise Exception
>> When an exception is raised, the entire stack frame at that location
>> (which includes local vars) is saved in the exception traceback. [...]
>> this is better:
>> def create():
>> f = file("tmp", "w")
> Why should this work? If I replace "do_stuff_that_raises_exception"
> with "raise Exception", it fails in the same way, since the file is
> open. Maybe you forgot "f.close()"?
I was puzzled by the same, but too lazy to try or ask. Anyhow, I think that
if you replaced the 'os.remove("tmp")' with 'f.close()', then the calling
function can remain the same as you wrote. This is basically the same as
when using the new-style "with", as mentioned by Gabriel.
Sator Laser GmbH
Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932
More information about the Python-list