ArithmeticError is the base class for exceptions that occur during arithmetic operations. Errors such as division by zero, floating-point overflow and floating-point underflow are derived from this exception class.
The following example raises a ZeroDivisionError, which is a subclass of ArithmeticError.
a = 10
b = 0
res = a / b
Output
ERROR!
Traceback (most recent call last):
File "<main.py>", line 3, in <module>
ZeroDivisionError: division by zero
Explanation:
- a / b attempts to divide 10 by 0.
- Division by zero is not allowed in Python.
- Python raises a ZeroDivisionError, which belongs to the ArithmeticError exception hierarchy.
Common Arithmetic-Related Errors
While working with mathematical operations, you may encounter errors caused by invalid calculations, incompatible operands, or floating-point limitations.
1. OverflowError: occurs when the result of a numeric operation exceeds the range that can be represented.
import math
res = math.exp(1000)
print(res)
Output
ERROR!
Traceback (most recent call last):
File "<main.py>", line 2, in <module>
OverflowError: math range error
Explanation: math.exp(1000) produces a value too large to be represented as a floating-point number.
2. FloatingPointError: occurs when floating-point operations fail and floating-point exception handling is enabled.
import numpy as np
np.seterr(all='raise')
try:
np.divide(1.0, 0.0)
except FloatingPointError:
print("Floating-point error occurred")
Output
Floating-point error occurred
Explanation: With np.seterr(all='raise'), NumPy raises a FloatingPointError instead of returning special values such as inf.
Errors Often Confused with ArithmeticError
The following errors may occur during calculations, but they are not subclasses of ArithmeticError.
1. ValueError: occurs when a function receives a valid data type but an invalid value.
num = int("abc")
Output
ERROR!
Traceback (most recent call last):
File "<main.py>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'abc'
Explanation: int() can convert strings containing numbers, but "abc" is not a valid numeric value.
2. TypeError: occurs when an operation is performed on incompatible data types.
a = "10"
b = 5
res = a + b
Output
ERROR!
Traceback (most recent call last):
File "<main.py>", line 3, in <module>
TypeError: can only concatenate str (not "int") to str
Explanation: Python cannot add a string ("10") and an integer (5) directly.