By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
448,571 Members | 1,265 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 448,571 IT Pros & Developers. It's quick & easy.

Exception handling code (try/except/finally)

P: n/a
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


Jul 18 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
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
Jul 18 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.