I'm learning to use python. I just came across this article: http://nedbatchelder.com/blog/200711/rethrowing_exceptions_in_python.html It describes rethrowing exceptions in python, like this:
try:
do_something_dangerous()
except:
do_something_to_apologize()
raise
Since you re-throw the exception, there should be an "outer catch-except" statement. But now, I was thinking, what if the do_something_to_apologize()
inside the except throws an error. Which one will be caught in the outer "catch-except"? The one you rethrow or the one thrown by do_something_to_apologize()
?
Or will the exception with the highest priotiry be caught first?
Try it and see:
The result:
The reason: the "real" error from the original function was already caught by the
except
.apologize
raises a new error before theraise
is reached. Therefore, theraise
in theexcept
clause is never executed, and only the apology's error propagates upward. Ifapologize
raises an error, Python has no way of knowing that you were going to raise a different exception afterapologize
.Note that in Python 3, the traceback will mention both exceptions, with a message explaining how the second one arose:
However, the second exception (the "apology" exception) is still the only one that propagates outward and can be caught by a higher-level
except
clause. The original exception is mentioned in the traceback but is subsumed in the later one and can no longer be caught.