Exception handling code (try/except/finally)

djw dwelch at vcd.hp.com
Mon Mar 7 19:04:26 EST 2005


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







More information about the Python-list mailing list