Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
296 views
in Technique[技术] by (71.8m points)

exception - 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)
question from:https://stackoverflow.com/questions/65869448/how-to-print-every-error-using-try-except-in-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...