How do you catch multiple exception types with a single except clause?
Short answer
List the exception types as a TUPLE after 'except', separated by commas — the clause catches ANY of the listed types, running the same handling code regardless of which specific one was raised.
Advertisement
AModel answer
List the exception types as a TUPLE after 'except', separated by commas — the clause catches ANY of the listed types, running the same handling code regardless of which specific one was raised.
try:
value = int(user_input)
result = 10 / value
except (ValueError, ZeroDivisionError) as e:
print(f"Invalid input: {e}")Real-world example
Handling several related error conditions (like invalid input format AND division by zero) with the same recovery logic.
Likely follow-ups
- How would you handle these SAME exception types differently, with SEPARATE recovery logic for each?
Related topics