Regarding exception handling
belred at gmail.com
Mon Jan 31 02:26:16 EST 2005
Fredrik Lundh wrote:
> "Bryan" wrote
>>the above is not the same. make the a = ... raise an exception and you'll see the difference.
>>s = ... #
>>a = 1/0
>>as you can see, s.close() will never be called. also, in this example, i intentionally didn't put
>>the extra try/except around the try/finally statement.
> file handles and sockets are closed when the objects are garbage collected.
> under CPython, they're usually closed when they go out of scope.
> using try/finally on files and sockets are usually overkill.
i was trying to be generic and use the term resource. i know you are correct
about file handles and sockets. there are other resources that don't behave so
nicely. i'm currently using a third party module that will crash python (the
entire interpreter GPF's) if you don't explicitly close the resource before your
python script exits. other times, depending on a variable to go out of scope to
have a resource automically close itself is not practical. or sometimes you
want a resource to be closed, but still hold on to the reference. so, i don't
feel as strongly as you do that try/finally on even files and socks are
overkill. of course on small scripts, i don't use try/finally or close() either :)
More information about the Python-list