How to handle ZeroDivisionError in Python
Wrap a division operation in try/except to return None or a friendly message instead of crashing when dividing by zero.
Python code
22 linesdef safe_divide(a, b):
"""Return a/b if possible, else None when dividing by zero."""
try:
return a / b
except ZeroDivisionError:
return None
def safe_divide_with_message(a, b):
"""Return a how-to message on divide-by-zero error."""
try:
return a / b
except ZeroDivisionError:
return "Division by zero is not allowed."
if __name__ == "__main__":
# Demonstrations with clear, deterministic results
print(safe_divide(10, 2)) # 5.0
print(safe_divide(10, 0)) # None
print(safe_divide_with_message(8, 0)) # Division by zero is not allowed.
print(safe_divide(7, 3.5)) # 2.0
Output
5.0
None
Division by zero is not allowed.
2.0
How it works
The try block attempts the division, and if b is zero, Python raises a ZeroDivisionError. The except clause catches only that specific error, leaving other exceptions (like TypeError) to propagate. Returning None from the handler lets the caller detect the failure without an exception, which keeps control flow explicit. Adding a custom message is useful for user-facing feedback where a silent None would be confusing.
Common mistakes
- Catching `Exception` broadly instead of the specific `ZeroDivisionError`
- Forgetting to return a value in the except branch, which implicitly returns None but may be unclear
- Not using `try/except` when the divisor could be user input
Variations
- Use `math.isclose(b, 0)` to check before dividing, but beware floating-point edge cases.
- Raise a custom exception instead of returning None to force error handling upstream.
Real-world use cases
- Calculating percentages or ratios from user-provided data where a zero total is possible.
- Computing average response times in a metrics collector where an empty batch yields zero count.
- Parsing CSV files with possibly missing or zero denominators during data cleaning.
Sponsored
More from Errors & debugging
- Catch RecursionError and Fail Gracefully in Python easy
- Catch ValueError and print friendly message in Python easy
- Collect Multiple Validation Errors in Python Before Raising medium
- Handle ValueError and ZeroDivisionError in Python with try except easy
- How to Add a Correlation ID to Logging Records in Python medium
- How to Assert Preconditions with Descriptive Messages in Python easy
Keep learning
Related tutorials and quizzes for this topic.