Handling Multiple Exceptions
Handle multiple exception types in different ways, or group related exceptions together.
10 min•By Priygop Team•Updated 2026
Multiple Exceptions
Multiple Exceptions
# Catch multiple exceptions separately
def process_data(data):
try:
value = int(data)
result = 100 / value
items = [1, 2, 3]
return items[value]
except ValueError:
return "Not a number"
except ZeroDivisionError:
return "Cannot divide by zero"
except IndexError:
return "Index out of range"
except Exception as e:
return f"Unexpected: {e}"
print(process_data("hello")) # Not a number
print(process_data("0")) # Cannot divide by zero
print(process_data("10")) # Index out of range
print(process_data("2")) # 3 (items[2])
# Group exceptions
try:
result = int("abc") / 0
except (ValueError, ZeroDivisionError) as e:
print(f"Math error: {e}")
# Re-raising exceptions
def validate(value):
try:
if value < 0:
raise ValueError("Negative!")
except ValueError:
print("Logging the error...")
raise # re-raise the same exception
try:
validate(-5)
except ValueError as e:
print(f"Caught: {e}")Tip
Tip
Use tuple of exceptions to catch multiple types: except (ValueError, TypeError) as e:. Handle each type differently if needed.
Diagram
Loading diagram…
Catch specific exceptions. Use else for success logic. finally for cleanup. Custom exceptions for your domain.
Common Mistake
Warning
Catching too broadly with except Exception:. Be specific about what you expect. Unexpected errors should propagate up.
Practice Task
Note
(1) Handle multiple exception types. (2) Use except (TypeError, ValueError):. (3) Re-raise after logging.