Python Reference ยท Exceptions
Python ZeroDivisionError and ArithmeticError
Reference for Python ZeroDivisionError, OverflowError, FloatingPointError and their base ArithmeticError: what raises them, safe division and float edge cases.
ArithmeticError is the base class for errors in numeric calculations. It has three built-in subclasses: ZeroDivisionError, OverflowError and FloatingPointError. Catching ArithmeticError handles all of them at once.
ZeroDivisionError is by far the most common. It is raised when the right operand of /, //, % or divmod() is zero, and also for 0 ** -1 and 0.0 ** -1.
10 / 0 # ZeroDivisionError: division by zero 10 % 0 # ZeroDivisionError: division by zero
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
try: result = numerator / denominator except ZeroDivisionError: result = None except ArithmeticError as error: print("other arithmetic problem:", error)
| Class | Raised when |
|---|---|
ZeroDivisionError |
A divisor is zero in /, //, %, divmod(), pow() with a negative power of zero. |
OverflowError |
A result is too large for its type, such as 2.0 ** 10000 or math.exp(1000). |
FloatingPointError |
Only if floating-point checking is enabled by a library; plain Python never raises it. |
Hierarchy: Exception โ ArithmeticError โ ZeroDivisionError, OverflowError, FloatingPointError.
Usage notes
- Integers never overflow. Python integers grow as needed, so
OverflowErrorshows up only with floats and some C-level functions. - Floats and zero.
10.0 / 0.0also raisesZeroDivisionErrorin plain Python (unlike many languages, which return infinity). Infinity comes fromfloat("inf")or from overflow-free operations such as1e308 * 10. - Libraries differ. NumPy returns
infornanwith a warning instead of raising, so the same expression can behave differently in NumPy code. - Check before dividing when an empty collection is a normal case (average of an empty list). Use
try/exceptwhen zero is rare and the check would clutter the code. - Message wording varies. You may see
division by zero,integer division or modulo by zeroorfloat modulo, depending on the operation and version, so never match on message text. - Decimals and fractions raise their own:
decimal.DivisionByZero(a subclass ofZeroDivisionError) andZeroDivisionErrorforFraction(1, 0). - Do not return
0as a silent default unless zero is a meaningful answer;Noneor an explicit message is usually safer. - Comparisons are safe.
x == 0andx != 0never raise; guard with them or with truthiness (if divisor:).