[Solved] Python OverflowError: (34, ‘Result too large’)

Python OverflowError

Python OverflowError is raised when the result of a numeric calculation is too large to store.

Python OverflowError is one of the three sub-classes of ArithmeticError.

In this tutorial, we will go through an example that raises OverflowError, and then learn how to use try except statement to handle OverflowError.

Program that throws OverflowError

In the following program, we will try to find the power of 8 recursively to the power of numbers ranging from 1 to 100.

Python Program

n = 8.0
for i in range(1, 100):
    n = n ** i
Run Code Copy

Output

Traceback (most recent call last):
  File "/Users/arjun/Desktop/Projects/Python/example.py", line 3, in <module>
    j = j**i
OverflowError: (34, 'Result too large')

Handle OverflowError

In the following program, we will surround the code, that could raise OverflowError, in try block, and handle the error in except block.

Python Program

n = 8.0
try: 
    for i in range(1, 100):
        n = n ** i
except OverflowError as e:
    print('Its an Overflow error, please check.')
Run Code Copy

Output

Its an Overflow error, please check.

Handle OverflowError using ArithmeticError

Since OverflowError is a sub-class of ArithmeticError, we can match the except ArithmeticError for OverflowError.

Python Program

n = 8.0
try: 
    for i in range(1, 100):
        n = n ** i
except ArithmeticError as e:
    print('Its an Arithmetic error, please check.')
Run Code Copy

Output

Its an Arithmetic error, please check.

Summary

In this tutorial of Python Examples, we learned how OverflowError is raised, and how to handle an OverflowError, with the help of examples.

Related Tutorials

Code copied to clipboard successfully 👍