What's the use of the else in try/except/else?

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Tue May 12 05:35:36 EDT 2009


On Tue, 12 May 2009 09:20:36 +0000, Steven D'Aprano wrote:

> On Tue, 12 May 2009 20:23:25 +1200, Lawrence D'Oliveiro wrote:
> 
>> In message <gu7f97$mt6$2 at reader1.panix.com>, kj wrote:
>> 
>>> I know about the construct:
>>> 
>>> try:
>>>     # do something
>>> except ...:
>>>     # handle exception
>>> else:
>>>     # do something else
>>> 
>>> ...but I can't come with an example in which the same couldn't be
>>> accomplished with [no else]
>> 
>> I'd agree. If you have to resort to a "try .. else", then might I
>> respectfully suggest that you're using exceptions in a way that's
>> complicated enough to get you into trouble.
> 
> 
> 
> try:
>     rsrc = get(resource)
> except ResourceError:
>     log('no more resources available')
>     raise
> else:
>     do_something_with(rsrc)
> finally:
>     rsrc.close()



Except of course such a pattern won't work, because if get(resource) 
fails, rsrc will not exist to be closed. So a better, and simpler, 
example would be to drop the finally clause:

try:
    rsrc = get(resource)
except ResourceError:
    log('no more resources available')
    raise
else:
    do_something_with(rsrc)
    rsrc.close()


To really be safe, that should become:

try:
    rsrc = get(resource)
except ResourceError:
    log('no more resources available')
    raise
else:
    try:
        do_something_with(rsrc)
    finally:
        rsrc.close()


which is now starting to get a bit icky (but only a bit, and only because 
of the nesting, not because of the else).



-- 
Steven



More information about the Python-list mailing list