Skip to content
Advertisement

How to print every error using try except in python

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)

Advertisement

Answer

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
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement