Catch OverflowError Exception in Python



When an arithmetic operation exceeds the limits of the variable type, an OverflowError is raised. Long integers allocate more space as values grow, so they end up raising MemoryError. Floating point exception handling is not standardized, however. Regular integers are converted to long values as needed.

Using try-except to Catch OverflowError

You can use a try-except block to catch an OverflowError and prevent your program from crashing when a calculation overflows.

Example: Catching an OverflowError

In this example, we calculate a very large exponent which can cause an OverflowError on some systems, and catch it -

try:
   result = 10.0 ** 1000
except OverflowError:
   print("OverflowError caught: number too large.")

The output is -

OverflowError caught: number too large.

Capturing the Exception Object

You can also capture the exception object to get more details about the error. This allows you to access the specific error message and use it for logging or displaying more informative feedback.

Example

In this example, we catch the exception and print its message for more information -

try:
   result = 2.0 ** 10000
except OverflowError as e:
   print("Caught OverflowError:", e)

The output will be -

Caught OverflowError: (34, 'Numerical result out of range')

When does OverflowError Occur?

OverflowError usually happens when a floating-point calculation results in a number too large for the computer or Python to handle.

Example

In this example, a very large floating-point operation causes the exception -

import math

try:
   math.exp(1000)
except OverflowError as e:
   print("OverflowError caught:", e)

The output is -

OverflowError caught: math range error

Handling OverflowError in Calculations

To prevent program termination due to overflow, catch the exception and handle it, such as by using fallback values or error messages.

Example

In this example, we handle an overflow by returning infinity instead of letting the program crash -

import math

def safe_exp(x):
   try:
      return math.exp(x)
   except OverflowError:
      return float('inf')

print(safe_exp(700))  # Very large input

The output is -

1.0142320547350045e+304
Updated on: 2025-05-26T13:34:21+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements