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.

InheritsBaseException›Exception›ArithmeticError›ZeroDivisionError
Arithmetic exceptionPython 3 (all)Live demo
ZeroDivisionError(*args)
Raised by
x / 0, x // 0, x % 0, divmod(x, 0), 0 ** -1
Message
division by zero · float division by zero · integer modulo by zero …
Quick fix
check the divisor: a / b if b else 0.0
Watch out
float 0.0 raises too — no inf like JavaScript or NumPy

Demo

Live evaluation
Pick an operator: /, // or %. With b = 0 each one has its own message.
Try:
Inputs
opstr/ // %
aintdividend
bintdivisor
Code
import operator
ops = {'/': operator.truediv, '//': operator.floordiv, '%': operator.mod}
ops['/'](7, 0)
Uncaught exception
ZeroDivisionError: division by zero

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

NameTypeRequiredDescription
*argsobjectnoUsually one message string. str(e) is that message.

Attributes

AttributeTypeMeaning
argstupleargs[0] is the message string. There is no attribute holding the operands.
__context__BaseException | NoneThe exception being handled when this one was raised (implicit chaining).

Common patterns

Guard the divisor
When zero is an expected input (empty list, no visits), decide the answer explicitly.
rate = hits / total if total else 0.0
Average of a possibly empty list
len(xs) is 0 for an empty list; return a sentinel or raise a clearer error.
def mean(xs):
    if not xs:
        raise ValueError('mean of empty list')
    return sum(xs) / len(xs)
Percent change
A zero baseline has no meaningful percentage; None is more honest than 0.
def pct_change(old, new):
    return None if old == 0 else (new - old) / old * 100

Examples

1. Int true division
1 / 0
Returns
ZeroDivisionError: division by zero
2. Float operand
1.0 / 0
Returns
ZeroDivisionError: float division by zero
3. Floor division
1 // 0
Returns
ZeroDivisionError: integer division or modulo by zero
4. Modulo
1 % 0
Returns
ZeroDivisionError: integer modulo by zero
5. divmod() on floats
divmod(1.0, 0)
Returns
ZeroDivisionError: float divmod()
6. Zero to a negative power
0 ** -1
Returns
ZeroDivisionError: 0.0 cannot be raised to a negative power
7. Mean of an empty list
def mean(xs): return sum(xs) / len(xs) mean([])
Returns
ZeroDivisionError: division by zero
8. Decimal raises a subclass
from decimal import Decimal try: Decimal(1) / 0 except ZeroDivisionError as e: r = type(e).__name__ r
Returns
'DivisionByZero'

Pitfalls

1. Expecting inf like JavaScript or NumPy
Plain Python floats raise on division by zero, even 1 / 0.0 and 1 / -0.0. Use math.inf explicitly if that is the answer you want.
1 / 0.0
1 / 0.0
ZeroDivisionError: float division by zero
Decide the result
import math
d = 0.0
r = 1 / d if d else math.inf
r
inf
2. A wide try hides which division failed
Catching ZeroDivisionError around a whole computation replaces every failure with the fallback — including bugs. Test the specific divisor.
Blanket fallback
def ratio(a, b, c):
    try:
        return a / b + b / c
    except ZeroDivisionError:
        return 0.0
ratio(1, 2, 0)
0.0
Guard the divisor
def ratio(a, b, c):
    return a / b + (b / c if c else 0.0)
ratio(1, 2, 0)
0.5
3. Rounding error is not zero
A float that should be 0 often is not, so the division succeeds with a huge result. Compare with a tolerance before dividing.
Tiny but non-zero
d = 0.1 + 0.2 - 0.3
1 / d
1.8014398509481984e+16
math.isclose
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
True

When to use

Use it
  • 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
Reach for something else
  • 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

Messages
int: division by zero (/), integer division or modulo by zero (//, divmod), integer modulo by zero (%). float: float division by zero, float floor division by zero, float modulo by zero, float divmod()
Catch via
except ArithmeticError also catches OverflowError and FloatingPointError
Decimal
decimal.DivisionByZero subclasses both decimal.DecimalException and ZeroDivisionError
Not raised
math.fmod(x, 0) and math.log(0) raise ValueError: math domain error instead

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.