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 IndexError
message and ZeroDivisionError
message?
Below is the code I wrote.
JavaScript
x
9
1
try:
2
a = [1,2]
3
print(a[3])
4
4/0
5
except ZeroDivisionError as e:
6
print(e)
7
except IndexError as e:
8
print(e)
9
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
JavaScript
1
11
11
1
try:
2
a = [1, 2]
3
print(a[3])
4
except IndexError as e:
5
print(e)
6
7
try:
8
4 / 0
9
except ZeroDivisionError as e:
10
print(e)
11
Giving
JavaScript
1
3
1
list index out of range
2
division by zero
3