preserve exception within try .. finally

Peter Otten __peter__ at web.de
Fri Oct 10 17:06:07 EDT 2003


Brian Alexander wrote:

> I'm curious to know how people preserve exceptions that arise in a try
> .. finally block. Consider this example:
> 
> try:
>    getResource()
>    doSomething()
> finally:
>    alwaysFreeResource()
> 
> If an exception occurs in doSomething(), the resource is freed anyway --
> which is good. How can I keep the exception 'raised' for another
> try-finally/except to deal with? Does this problem reflect an error in
> the way I am approaching the problem?

The exception raised by doSomething() travels all the way up the call stack
until it hits an except clause that can catch it, i. e. 

except ExceptionRaised:
    # handle it

or

except SuperClassOfExceptionRaised:
    # handle it

All the finally blocks that lie on the way up are executed.
Note that the correct use of try... finally is

getResource() # don't free if it cannot be acquired
try:
    doSomething()
finally
    freeResource()

This will typically be included (not necessarily in the same function) by a
try ... except

try:
    getResource()
    try:
        doSomething()
    finally
        freeResource()
except SomeException, e:
    if canHandleIt(e):
        #handle it
    else:
        raise # hope for another handler 

I think that the canHandleIt(e) test and the reraising is not very common,
but I included it as you were asking for "keeping it raised", which might
translate into "reraising it".

Peter











More information about the Python-list mailing list