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.

Easy Python 3.9+ Aug 9, 2026 Errors & debugging 13 views 0 copies

Python code

22 lines
Python 3.9+
def 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

stdout
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

  1. Use `math.isclose(b, 0)` to check before dividing, but beware floating-point edge cases.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Errors & debugging

Related tutorials and quizzes for this topic.