ArithmeticError
ArithmeticError
Traceback
Traceback (most recent call last):
File "main.py", line 2, in <module>
return a / b # may raise ZeroDivisionError or OverflowError
ArithmeticErrorWhat causes this error
A numeric computation failed. This is the base class for ZeroDivisionError, OverflowError, and FloatingPointError. It is not usually raised directly.
How to fix it
Catch ArithmeticError to handle all numeric computation failures uniformly. For more specific handling, catch ZeroDivisionError or OverflowError individually. Validate inputs before performing calculations.
Code that causes this error
def safe_divide(a, b):
return a / b # may raise ZeroDivisionError or OverflowErrorFixed code
def safe_divide(a, b, default=0):
try:
return a / b
except ArithmeticError:
return defaultAbout ArithmeticError
ArithmeticError is the base class for exceptions raised by arithmetic operations. It is the parent of ZeroDivisionError, OverflowError, and FloatingPointError. Like LookupError, ArithmeticError itself is rarely raised directly — you typically encounter its subclasses.
Catching ArithmeticError is useful when you want to handle any numeric computation failure uniformly, such as in calculator applications, data processing pipelines, or mathematical libraries where the specific type of arithmetic failure does not change the recovery strategy. FloatingPointError (the third subclass) is only raised when Python is configured to enable floating-point exception trapping, which is off by default. In practice, catching ZeroDivisionError and OverflowError individually is more common than catching ArithmeticError.
Common scenarios
Computing averages or percentages where the denominator can be zero
Passing extremely large values to math library functions
Performing calculations that exceed float precision limits
Division operations on user-provided input without validation