OverflowError
PythonERRORCriticalArithmetic ErrorMEDIUM confidence

Result of an arithmetic operation is too large to be represented

What this means

Raised when the result of an arithmetic operation is too large to be represented by the relevant numeric type. This is rare for standard integers in Python 3 but can occur with floats or other types.

Why it happens
  1. 1Multiplying or exponentiating very large floating-point numbers.
  2. 2A calculation that should mathematically approach infinity.
  3. 3Converting a very large Python integer to a fixed-size C type in an extension module.
How to reproduce

This error occurs when a floating-point calculation exceeds the maximum representable value for a float.

trigger — this will error
trigger — this will error
import math
# The result of math.exp(1000) is larger than can be stored in a float
try:
    result = math.exp(1000)
except OverflowError as e:
    print(f"Caught OverflowError: {e}")

expected output

Caught OverflowError: math range error

Fix 1

Check input values before the operation

WHEN You can anticipate that certain inputs will lead to an overflow.

Check input values before the operation
import math
value = 1000
if value > 709: # math.log(sys.float_info.max) is approx 709.78
    print("Input is too large, will cause overflow.")
else:
    result = math.exp(value)

Why this works

By validating the input against a known threshold, you can avoid performing the calculation that would raise the error.

Fix 2

Use data types that support arbitrary precision

WHEN You need to work with numbers larger than standard floats allow.

Use data types that support arbitrary precision
from decimal import Decimal, getcontext
# Set precision for the Decimal type
getcontext().prec = 50 
# This calculation will work with the Decimal type
large_number = Decimal(1000)
result = large_number.exp()

Why this works

The `Decimal` type is designed to handle floating-point arithmetic with user-defined precision, allowing for calculations far beyond the limits of standard floats.

Code examples
Triggerpython
import math
result = math.exp(1000)  # OverflowError: math range error
Handle with try/exceptpython
import math
try:
    result = math.exp(val)
except OverflowError:
    result = float("inf")
Avoid with input validationpython
import math, sys
MAX_EXP = math.log(sys.float_info.max)  # ~709.78
result = math.exp(val) if val <= MAX_EXP else float("inf")
What not to do

Ignoring the error

An `OverflowError` indicates a significant loss of precision or an invalid calculation. Ignoring it means your program will proceed with incorrect data, leading to flawed results.

Version notes

Sources
Official documentation ↗

cpython/Objects/exceptions.c

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Python errors