Can I catch multiple exceptions per line?

Asked 1 years ago, Updated 1 years ago, 87 views

I want to do the same thing for err1 and err2 Do I have to write it separately like that?

try:
    # Error Code
except err1 :
    pass
except err2 :
    pass

python exception exception-handling

2022-09-21 15:39

1 Answers

The method is slightly different depending on the Python version.

#Method1 
try:
    print(1/0)
except (ZeroDivisionError, ArithmeticError) :
    print(3)


#How2
try:
    print(1/0)
except ZeroDivisionError, ArithmeticError :
    print(3)

Method 1 and 2 differ only in parentheses. Python 2.6 and 2.7 are both ways If it's Python 3 or higher, you can only use Method 1.


2022-09-21 15:39

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.