try:
raise KeyError()
except KeyError:
print "Caught KeyError"
raise Exception()
except Exception:
print "Caught Exception"
As expected, raising Exception() on the 5th line isn't caught in the final except Exception clause. In order the catch the exception inside of the except KeyError block, I have to add another try...except like this and duplicate the final except Exception logic:
try:
raise KeyError()
except KeyError:
print "Caught KeyError"
try:
raise Exception()
except Exception:
print "Caught Exception"
except Exception:
print "Caught Exception"
In Python, is it possible to pass the flow of execution to the final except Exception block like I am trying to do? If not, are there strategies for reducing the duplication of logic?
Exceptionin a function. Then call that function in both places.exceptclauses only catch errors thrown in thetry; otherwise, you couldn't re-raise if you wanted to.raise, without anything else. That may or may not fit your reqs in this case. Can't tell from your code alone.