Regarding exception handling

Bryan belred at
Mon Jan 31 01:53:40 EST 2005

Dan Perl wrote:
> "Bryan" <belred at> wrote in message 
> news:mailman.1614.1107137827.22381.python-list at
>>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 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. 
    usually i let an exception caused by s = ... to bubble up to some level that 
knows how to handle that error.  we are talking about a resource here and in my 
experience, these low level functions (below the UI or management layer) don't 
know how to or shouldn't handle resources that can't be opened.


> 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