Back to Feed

ZeroDivisionError when dividing by zero in Python function

@Deep Chauhan

Python 3.x (e.g., 3.11) script executed on a standard CPython interpreter. No external libraries are used. The function `divide` is intended to perform arithmetic division and is called with user‑provided arguments. The environment is a simple command‑line execution, so any uncaught exception terminates the process with a traceback.

The Bug / Incident

Traceback (most recent call last): File "script.py", line 5, in <module> print(divide(10, 0)) File "script.py", line 2, in divide return a / b ZeroDivisionError: division by zero

The Investigation / Logic

1. The function `divide(a, b)` directly returns `a / b` without any validation. 2. In Python, the `/` operator raises a `ZeroDivisionError` when the divisor `b` is zero. This exception propagates up the call stack because it is not caught inside the function. 3. The script calls `divide(10, 0)`, triggering the exception, which aborts the program and prints the traceback shown above. 4. To prevent the crash, we need to guard against a zero divisor before performing the division. 5. Two common strategies exist: - Raise a custom exception or re‑raise `ZeroDivisionError` with a clearer message. - Return a sentinel value (e.g., `None` or an error string) that the caller can inspect. 6. The provided "solution" chooses the second strategy: it checks `b == 0` and returns a human‑readable error string. This eliminates the exception and allows the program to continue execution, printing the error message instead of a traceback. 7. The fix is straightforward, but we must consider type consistency: callers expecting a numeric result will now receive a string, which could cause downstream type errors if not handled.

The Fix / Resolution

The Fix / Solution

python
def divide(a, b):
    """Return the result of a / b, handling division‑by‑zero gracefully.

    Args:
        a (float or int): Numerator.
        b (float or int): Denominator.

    Returns:
        float: The division result when b != 0.
        str: An error message when b == 0.
    """
    if b == 0:
        return "Error: cannot divide by zero"
    return a / b

# Example usage
print(divide(10, 0))  # -> Error: cannot divide by zero
print(divide(10, 2))  # -> 5.0