Exception handling code (try/except/finally)

D

djw

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
 
M

Michael Hoffman

djw said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top