0

I'm now learning how to handle multiple errors in python. While using try-except I want to print every error in try. There are two errors in try but the indexing error occurred first, so the program can't print a message about ZeroDivisionError. How can I print both IndexErrormessage and ZeroDivisionErrormessage?

Below is the code I wrote.

try:
    a = [1,2]
    print(a[3])
    4/0
except ZeroDivisionError as e:
    print(e)
except IndexError as e:
    print(e)

2 Answers 2

2

As the IndexError occurs, it goes to the except, so the 4/0 is not executed, the ZeroDivisionError doesn't occur, to get both executed, use 2 different try-except

try:
    a = [1, 2]
    print(a[3])
except IndexError as e:
    print(e)

try:
    4 / 0
except ZeroDivisionError as e:
    print(e)

Giving

list index out of range
division by zero
Sign up to request clarification or add additional context in comments.

Comments

2

You cannot do that, when the first error occurs, your code executes except block unless you define multiple try-except blocks.

Comments

Your Answer

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.