Re-raising the right exception

Duncan Booth duncan.booth at invalid.invalid
Thu Oct 21 19:12:51 CEST 2004


SM wrote:

> For example,
> 
> try:
>     network.command()
> except:
>     try:
>         network.close()
>     except:
>         pass
>     raise
> 
> I want to make a network call, and if it raises an exception, I want
> to close the network connection before allowing the exception to
> propagate up the stack. However, trying to close the network
> connection might itself raise an exception, and I don't care about
> that exception; I want to send the original exception. Apparently the
> way to do this is:
> 

<snip>

You could move the cleanup code out to another scope:

try:
    network.command()
except:
    def network_cleanup():
      try:
        network.close()
      except:
        pass

    network_cleanup()
    raise

In practice something like network_cleanup probably wants to be called from 
more than one place so it could be in a function defined elsewhere.

Another option is to use try..finally:

try:
    network.command()
finally:
    try:
        network.close()
    except:
        pass

then you don't need to reraise the exception at all.

Use the first suggestion if the cleanup only needs to be done when the code 
failed (e.g. to remove partially created files from disc). Use the second 
if the cleanup needs to be done always, e.g. closing files or network 
connections.



More information about the Python-list mailing list