Exception handling code (try/except/finally)

Michael Hoffman cam.ac.uk at mh391.invalid
Tue Mar 8 01:22:02 CET 2005


djw wrote:
> c.l.p-
> 
> I am having trouble understanding how one is supposed to correctly 
> utilize try:...except:...finally: in real code. If I have a block of 
> code like:
> 
> def foo():
>     try:
>         ... some code that can raise an exception ...
> 
>     finally:
>         ... do some cleanup ...
>         return something
> 
> If any exception occurs in the code inside the try:...finally:, it will 
> fail silently, which is a bad thing.

You want:

def foo():
     try:
         ...work...
     finally:
         ...cleanup...

     return something

By removing the return from the finally block you will still
automatically raise an exception when something goes wrong.
Having the return in the finally block prevents that from happening.
-- 
Michael Hoffman



More information about the Python-list mailing list