Regarding exception handling

Dan Perl danperl at rogers.com
Mon Jan 31 00:06:23 EST 2005


"Bryan" <belred at gmail.com> wrote in message 
news:mailman.1614.1107137827.22381.python-list at python.org...
> IMO, that is not the reason for the try/finally statement and it is not 
> redundant.  the try/finally statement guarantees the resource is closed 
> and the try/finally statement only gets executed if and only if the 
> opening of the resource doesn't raise an exception.  it has nothing to do 
> with exception handling.

But IMO, try-finally is meant to be used only if the block in the try clause 
may raise exceptions.  Here is an example that shows what I meant:
    s = ... # socket opens
    try:
        a = 1
    finally:
        s.close()

works perfectly the same as:
    s = ... # socket opens
    a = 1
    s.close()

The try-finally statement does not "handle" the exception, but it makes 
sense only if exceptions are possible.  There is no point in enclosing "a = 
1" in any kind of try statement.

According to a following posting from Angelos he did expect some other 
exceptions than socket.error and hence the nested try's.  To my defence 
though, I put in a disclaimer for that case in my initial posting.

> in the previous 2 examples s = ... was placed inside the try/finally, but 
> if an exception occures and s doesn't get bound to an object, then 
> s.close() in both examples will raise a NameError on s.

That is a very good point.  I missed it.

Dan 





More information about the Python-list mailing list