How to Solve OverflowError: math range error in Python

The OverflowError: math range error is a built-in Python exception raised when a math range exceeds its limit. There is a limit for storing values for every data type in Python. We can store numbers up to that limit. If the number exceeds the maximum limit, then the OverflowError is raised.

How to Solve OverflowError: math range error in Python

To solve OverflowError: math range error in Python, fit the data within the maximum limit. We must use different data types to store the value if this data cannot be fitted. When the data limit is exceeded, then it is called the overflow.

import math
ans = math.exp(1)



The output is printed as 2.718281828459045. This program is used for calculating the exponential value. 

import math
ans = math.exp(900)


OverflowError: math range error

It raises an error called the OverFlowError because the exponential value would have exceeded the data type limit.

To solve OverflowError programmatically, use the if-else statement in Python. We can create an if condition for checking if the value is lesser than 100. If the value is less than 100, it will produce an exponential value. And in the else block, we can keep a print statement like the value is too large for calculating the exponentials.

import math

num = 2000
if(num < 100):
  ans = math.exp(num)
  print("The value is too large, Please check the value")


The value is too large, Please check the value

Using the if-else statement, we can prevent the code from raising an OverflowError. 100 is not the end limit. It can calculate around 700, but running takes a lot of memory. 

One more way to solve this problem is by using try and except block. Then, we can calculate the exponent value inside the try block. Then, the exponent value is displayed if the value is less than the data limit.

If the value exceeds the limit, then except block is executed. OverflowError class name can be used to catch OverflowError.

import math

val = int(input("Enter a number: "))
 ans = math.exp(val)
except OverflowError:
 print("Overflow Error has occurred !")


Enter a number: 1000
Overflow Error has occurred !

In this program, if we give a value less than 700 or 500, this program works well and generates the output. However, if the value is equal to or greater than 1000, the error message will be displayed as output. We used the try and except block to solve this OverflowError


The OverflowError is raised when the value is greater than the maximum data limit. The OverflowError can be handled by using the try-except block. If and else statement can be used in some cases to prevent this error.

That’s it for this tutorial.

Related posts

How to Solve OverflowError: Python int too large to convert to C long

How to Solve ArithmeticError Exception in Python

How to Solve IndexError: list index out of range in Python

Leave a Comment