How to Solve ArithmeticError Exception in Python

ArithmeticError is the base class for all arithmetic-related errors. To solve ArtithmeticError in Python, use the try-except clause properly. Try and except statement is used to handle exceptions without terminating the program.

The ArithmeticError consists of three exceptions.

  1. ZeroDivisionError
  2. FloatingPointError
  3. OverFlowError

These three types of errors can be caught by a single exception called the ArithmeticError exception.

ZeroDivisionError in Python

The ZeroDivisionError is a type of exception raised when a number is divided by 0. In this type of error, the denominator should not be 0. If the value of the denominator is changed and other than 0, then the code works correctly. This is not a critical error. It is just an indication that a number is divided by 0.

Example

a = 5
b = 0

try:
   c = a/b
   print(c)
except ArithmeticError as e:
   print("Arithmetic Error is thrown")
   print(f"{e}, {e.__class_}")

Output

Arithmetic Error is thrown

Traceback (most recent call last):
 File "/Users/krunallathiya/Desktop/Code/R/data.py", line 4, in <module>
 c = a/b

ZeroDivisionError: division by zero

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
 File "/Users/krunallathiya/Desktop/Code/R/data.py", line 8, in <module>
 print(f"{e}, {e.__class_}")

AttributeError: 'ZeroDivisionError' object has no attribute '__class_'

The above code throws ZeroDivisionError: division by error, <class ‘ZeroDivisionError’>. When a number is divided by zero, this error is raised. This can be solved by replacing the denominator number.

You can directly use ZeroDivisionError in the except class. However, if you don’t know what error occurs, we can generally use ArithmeticError. Now, let’s see how to handle ZeroDivisionError.

a = 5
b = 0

try:
   c = a/b
   print(c)
except ZeroDivisionError:
   print("ZeroDivisionError is occurred. Please change the denominator value")

Output

ZeroDivisionError is occurred. Please change the denominator value

OverFlowError in Python

The OverFlowError exception in Python is thrown when a number exceeds its limit. Every number data type has some starting and ending limit, and if a number exceeds this limit, the OverFlowError exception is raised.

Example

import math

print("Simple program for showing overflow error")
print("\n")
print("The exponential value is")
print(math.exp(1000))

Output

Simple program for showing overflow error

The exponential value is
Traceback (most recent call last):
 File "/Users/krunallathiya/Desktop/Code/R/data.py", line 6, in <module>
 print(math.exp(1000))

OverflowError: math range error

You can see that it throws an OverflowError: math range error.

In the above program, we can see that we are importing a math module and using it to calculate exponential values such as exp(1000), which means e^x here x value is 1000 and e value is 2.7 where when are trying to calculate this. As a result, it is double, and it cannot print the result.

Therefore, it gives an OverflowError: math range error as seen in the above program, which says it is out of range because the x value is 1000, which when results give the value out of range or double to store the value and print it.

To solve the OverflowError: math range error in Python, use the try-except clause, and if it raises an exception, then handle it using except statement.

import math

try:
 result = math.exp(1000)
except OverflowError:
 result = float('inf')
print(result)

Output

inf

You can see that math.exp(1000) returns Infinity, and we handle it properly, then it won’t crash; otherwise, it returns the OverflowError, a type of ArithmeticError.

FloatingPointError in Python

This type of error is raised when a number has large decimal digits. A well-known example is when we divide 10 by 3. The decimal places go on like 3.333… hence this error can be rounded to the nearest number.

You can also trigger a FloatingPointError within numpy by setting the appropriate numpy.errstate flag.

import numpy as np

with np.errstate(invalid='raise'):
     np.sqrt(-1)

Output

FloatingPointError: invalid value encountered in sqrt

You can see that it throws a FloatingPointError: invalid value encountered in sqrt.

To solve FloatingPointError in Python, use the try-except statement.

import numpy as np

try:
  with np.errstate(invalid='raise'):
       np.sqrt(-1)
except FloatingPointError:
  print("Caught FloatingPointError")

Output

Caught FloatingPointError

This is one of the simplest ways to handle the FloatingPointError exception.

Conclusion

We saw all three ArithmeticError exceptions and how to handle them properly in Python.

  1. ZeroDivisionError
  2. OverflowError
  3. FloatingPointError

That’s it for this tutorial.

See also

TypeError: list indices must be integers or slices, not str

TypeError: Only size-1 arrays can be converted to Python scalars

Leave a Comment