I often find myself wanting to do something like this, I have something wrapped in try excepts like this
item= get_item()
try:
do_work(item)
except SomeError as err:
if err.code == 123:
do_something(item)
else:
# Actually I don't want to do something with this error code... I want to handle in 'except'
except:
put_back(item)
raise
Is there a way to raise into the except block below from the else? (a continue would be nice) I end up doing something like the following which isn’t as clean
item= get_item()
try:
try:
do_work(item)
except SomeError as err:
if err.code == 123:
do_something(item)
else:
raise
except:
put_back(item)
raise
Is there anyway to do that?
If you are using a recent enough python version (2.5 and up), you should switch to using a context manager instead:
Then:
The
__exit__method can return True if an exception has been handled; returning None will instead re-raise any exceptions raised in thewithblock.If not, you are looking for a
finallyblock instead:The
finallysuite is guaranteed to be executed when thetry:suite completes, or an exception has occurred. By settingitemtoNoneyou basically tell thefinallysuite everything completed just fine, no need to put it back.The
finallyhandler takes over from your blanketexcepthandler. If there has been an exception indo_work,itemwill not be set to None. If theSomeErrorhandler doesn’t catch the exception, orerr.codeis not 123,itemwill also not be set to None, and thus theput_back(item)method is executed.