Can a single try block have multiple except clauses in Python?
Can a single try block have multiple except clauses in Python?
Solution
A single try block can have any number of except clauses. Python checks them from top to bottom and runs the first one whose exception type matches the error raised. This lets you handle different exceptions differently.
try:
x = int(input())
y = 10 / x
except ValueError:
print("Not a number")
except ZeroDivisionError:
print("Cannot divide by zero")
Option 2: one except clause can also catch several types at once using a tuple, such as except (ValueError, TypeError):, so there is no single-type limit.
Option 3: nesting is not required. The multiple except clauses sit at the same level under one try.
Place specific exceptions before general ones like Exception, because a general clause placed first would catch everything and the later ones would never run.
Related questions:
2025: 15 May Shift 2