OverflowError Exception in Python

By Lenin Mishra

This is the part of the 9th day in the Python 30 series. Check out the series here.

An OverflowError exception is raised when an arithmetic operation exceeds the limits to be represented. This is part of the ArithmeticError Exception class.

Example 1

Code

j = 5.0

for i in range(1, 1000):
    j = j**i
    print(j)

Output

5.0
25.0
15625.0
5.960464477539062e+16
7.52316384526264e+83
Traceback (most recent call last):
  File "some_file_location", line 4, in <module>
    j = j**i
OverflowError: (34, 'Result too large')

As you can see, when you are trying to calculate the exponent of a floating point number, it fails at a certain stage with OverflowError exception. You can handle this error using the OverflowError Exception class in Python.

Example 2 - Handling OverflowError in Python

Code

j = 5.0

try:
    for i in range(1, 1000):
        j = j**i
        print(j)
except OverflowError as e:
    print("Overflow error happened")
    print(f"{e}, {e.__class__}")

Output

5.0
25.0
15625.0
5.960464477539062e+16
7.52316384526264e+83
Overflow error happened
(34, 'Result too large'), <class 'OverflowError'>

Check out other Python Built-in Exception classes in Python.

  1. Try, Except, Else and Finally in Python
  2. ZeroDivisionError Exception in Python
  3. KeyError Exception in Python
  4. ArithmeticError Exception in Python
  5. IndexError Exception in Python
  6. LookupError Exception in Python
  7. StopIteration Exception in Python
  8. TypeError Exception in Python
  9. NameError Exception in Python
  10. FileNotFoundError Exception in Python
  11. Catch Multiple Exceptions in Python