ZeroDivisionError
Dividing by zero raises instead of returning inf or NaN — for floats too. The message tells you which operator and which operand types were involved.
Demo
import operator ops = {'/': operator.truediv, '//': operator.floordiv, '%': operator.mod} ops['/'](7, 0)
With ints, / says division by zero, // says integer division or modulo by zero and % says integer modulo by zero — three messages for one mistake. With a float operand they become float division by zero, float floor division by zero and float modulo by zero. The -7 // 2 case is a reminder that // floors toward negative infinity: -4, not -3.
Constructor
| Name | Type | Required | Description |
|---|---|---|---|
| *args | object | no | Usually one message string. str(e) is that message. |
Attributes
| Attribute | Type | Meaning |
|---|---|---|
| args | tuple | args[0] is the message string. There is no attribute holding the operands. |
| __context__ | BaseException | None | The exception being handled when this one was raised (implicit chaining). |
Common patterns
rate = hits / total if total else 0.0
def mean(xs): if not xs: raise ValueError('mean of empty list') return sum(xs) / len(xs)
def pct_change(old, new): return None if old == 0 else (new - old) / old * 100
Examples
Pitfalls
1 / 0.0
import math d = 0.0 r = 1 / d if d else math.inf r
def ratio(a, b, c): try: return a / b + b / c except ZeroDivisionError: return 0.0 ratio(1, 2, 0)
def ratio(a, b, c): return a / b + (b / c if c else 0.0) ratio(1, 2, 0)
d = 0.1 + 0.2 - 0.3 1 / d
import math d = 0.1 + 0.2 - 0.3 r = None if math.isclose(d, 0, abs_tol=1e-9) else 1 / d r is None
When to use
- EAFP arithmetic where a zero divisor is truly exceptional
- Raising it from a custom numeric type's __truediv__ / __mod__
- Catching it at a boundary to report bad input
- Zero is a normal input (empty list, no traffic) → guard with if
- You want inf/nan semantics → use math.inf explicitly or NumPy
- Decimal code → configure the context traps instead of catching
Notes
FAQ
Find where the divisor became 0 — usually len() of an empty list, a counter that never incremented, or a value parsed from empty input. Then decide what the answer should be in that case: a guard like a / b if b else 0.0, returning None, or raising a clearer ValueError.