I have the code block like below:
try:
method()
except ErrorType1:
todo()
return
except ErrorType2 as e:
todo()
raise e
Basically for the two error types, I need to execute todo() first, then either return or raise e. Is it possible to just write todo() once? I was thinking using finally but don't think that actually works.
You could catch both exceptions in one
exceptclause, executetodoand then decide to do based on the exception type:Note - as pointed out by @ShadowRanger in the comments to the question - you should just use
raiseto re-raise the existing exception, usingraise ewill raise a second copy of it, resulting in the traceback including the line withraise eon it as well as the line where the original error occurred.