I don't understand the meaning of the last sentence below:
If an exception occurs in any of the clauses and is not handled, the exception is temporarily saved. The finally clause is executed. If there is a saved exception it is re-raised at the end of the finally clause. If the finally clause raises another exception, the saved exception is set as the context of the new exception.
Questions
Could someone please explain the meaning of the text in bold?
Also, what object is saved if an exception occurs in an
except
clause? Doesexcept
's exception replacetry
's?
When I try raising an exception in except
, both exceptions appear in the output:
try:
1/0
except ZeroDivisionError:
raise Exception("raised in except clause")
#-------------------------- Output ----------------------------
Traceback (most recent call last):
File "C:\Users\...\try.py", line 2, in <cell line: 1>
1/0
ZeroDivisionError: division by zero
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\...\try.py", line 4, in <cell line: 1>
raise Exception("raised in except clause")
Exception: raised in except clause
The same happens when I raise it in finally
(same input and output as above, but with "finally" in place of "except").