Floating-point operation failed
Production Risk
Rare in standard Python; more common when using the decimal module with traps enabled.
A subclass of ArithmeticError raised when a floating-point operation fails. In standard Python, this is rarely raised because the default IEEE 754 behavior returns inf or nan instead of raising. It only triggers when floating-point exceptions are explicitly enabled via the fpectl module (deprecated) or the decimal module.
- 1Floating-point traps explicitly enabled and an FP exception occurs
- 2Using the decimal module with a trap set for OVERFLOW, DIVISION_BY_ZERO, or INVALID_OPERATION
Decimal module with DivisionByZero trap enabled.
import decimal
ctx = decimal.getcontext()
ctx.traps[decimal.DivisionByZero] = True
decimal.Decimal('1') / decimal.Decimal('0')expected output
decimal.DivisionByZero: [<class 'decimal.DivisionByZero'>]
Fix 1
Check for zero before dividing
WHEN Performing floating-point division
import math
def safe_divide(a, b):
if b == 0.0 or math.isclose(b, 0.0):
return float('inf')
return a / bWhy this works
Guard division by zero explicitly; standard Python float division returns inf rather than raising.
Fix 2
Use math.isnan / math.isinf for result checking
WHEN After float arithmetic that might produce special values
import math
result = 1.0 / 0.0 # Returns inf in standard Python (no exception)
if math.isinf(result) or math.isnan(result):
result = 0.0 # or handle appropriatelyWhy this works
Standard Python float produces inf and nan instead of raising; always check results.
import decimal
ctx = decimal.getcontext()
ctx.traps[decimal.DivisionByZero] = True
decimal.Decimal("1") / decimal.Decimal("0") # FloatingPointErrorimport decimal
try:
result = x / y
except (ZeroDivisionError, decimal.FloatingPointError):
result = float("inf")import math
def safe_div(a, b):
if b == 0.0 or math.isclose(b, 0.0):
return float("inf")
return a / bPython Docs — Built-in Exceptions
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev