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.

So, the obvious thing to do (I think) is:

def foo():
        try:
                try:
                        ... some code that can raise an exception ...
                except someerror:
                        ... handle the error...
        finally:
                ... do some cleanup ...
                return something

But, now the finally doesn't really serve any purpose, if all the exceptions are handled by except:, finally will never be called as a result of an exception, only as the last statements of the function.

So, the next step is to do this?

def foo():
        try:
                try:
                        ... some code that can raise an exception ...
                except someerror:
                        ... handle the error...
                        raise someerror
        finally:
                ... do some cleanup ...
                return something

Which, I guess will work, but it feels very awkward. Is this the preferred/"correct" way to handle this? Is there a more elegant solution?

Also, why is this construct not possible?:

try:
        ... some code that can raise an exception ...
except someerror:
        ... handle the error...
finally:
        ... do cleanup, etc. ...


Thanks,

Don




-- http://mail.python.org/mailman/listinfo/python-list

Reply via email to