0

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?

asked Mar 14, 2020 at 23:32

1 Answer 1

1

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.

answered Mar 14, 2020 at 23:45
Sign up to request clarification or add additional context in comments.

1 Comment

Oh I see I should pause it for today. Totally clear for the first example. But thanks alot for the explanation for the second example. Made it clear!

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.