Reputation: 37
So I have following two different try-except blocks, where I do not understand the output and I believe it is because of Exceptions within except blocks. Even though I found a few questions with a similar title, they did not help me answering my question.
First block:
try:
try:
raise IndexError
x = 5/0
except ArithmeticError:
print("1")
print("2")
except IndexError:
print("3")
finally:
print("4")
except:
print("5") #Output: 3 4
Since we caught the IndexError, why does the last exception 5?
(I do understand that the raise IndexError
is caught by the second except and we get the 3, and since finally is always executed, 4 is printed out aswell).
Second (related) Question:
try:
try:
x = 5/0
except ArithmeticError:
print("1")
raise IndexError # this is different this time!
print("2")
except IndexError:
print("3")
finally:
print("4")
except:
print("5") #Output: 1 4 5
How is it, that the raise IndexError
does not execute the print("3")
statement? And why do we get the 5 output this time, since we did not get it in the first example?
Upvotes: 0
Views: 69
Reputation: 219077
except
will catch exceptions thrown in the try
, but not in other sibling except
blocks. For any given try
with multiple sibling except
blocks, one of those except
blocks will handle the exception.
In your first example 5
is not printed because the code within the outer try
does not throw an exception. An exception in the inner try
is thrown, and is handled by one of the except
blocks at that level.
In your second example 3
is not printed because the code in the try
block does not throw an IndexError
. It throws an ArithmeticError
, which is caught by the corresponding except
block. That block then also throws an exception, which exist the entire try/except
structure and gets caught by a higher except
block.
Upvotes: 1