In Python, you can catch multiple exceptions in a single except
block by specifying the exceptions as a tuple. This allows you to handle multiple error types with the same logic. Here’s how to do it:
Syntax
try:
# Code that might raise exceptions
except (Exception1, Exception2, ...) as e:
# Handle all listed exceptions here
Examples
1. Catch ValueError
and TypeError
:
try:
num = int("abc") # Raises ValueError
except (ValueError, TypeError) as e:
print(f"Error: {e}") # Output: Error: invalid literal for int() with base 10: 'abc'
2. Catch KeyError
and IndexError
:
my_dict = {"name": "Alice"}
my_list = [1, 2, 3]
try:
print(my_dict["age"]) # Raises KeyError
# print(my_list[10]) # Raises IndexError
except (KeyError, IndexError) as e:
print(f"Missing key or index: {e}")
3. Combine built-in and custom exceptions:
class CustomError(Exception):
pass
try:
raise CustomError("Oops!")
except (RuntimeError, CustomError) as e:
print(f"Caught error: {e}") # Output: Caught error: Oops!
Key Notes
- Parentheses are required around the tuple of exceptions.
❌ Incorrect:except ValueError, TypeError
✅ Correct:except (ValueError, TypeError)
- Use
as e
to access the exception object (e.g., for logging or error messages). - Order matters if exceptions are related by inheritance. For example, catching
Exception
first will supersede more specific exceptions.
When to Use This?
- When multiple exceptions require identical handling (e.g., logging, cleanup, or a fallback value).
- To reduce code duplication for similar error types.
Avoid Catching All Exceptions
Never use a bare except:
or except Exception:
unless intentional, as it hides unexpected errors:
# ❌ Avoid this unless necessary
try:
risky_operation()
except: # Catches ALL exceptions (even KeyboardInterrupt!)
print("Something went wrong")
Handling Exceptions Differently
If you need to handle exceptions separately, use multiple except
blocks:
try:
# Code
except ValueError:
print("Value error!")
except TypeError:
print("Type error!")
Real-World Example
def divide(a, b):
try:
return a / b
except (ZeroDivisionError, TypeError) as e:
return f"Error: {e}"
print(divide(10, 0)) # Error: division by zero
print(divide("10", 2)) # Error: unsupported operand type(s) for /: 'str' and 'int'
By grouping exceptions in a tuple, you streamline error handling while keeping your code clean and maintainable!