Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to catch ArithmeticError Exception in Python?
While executing statements that perform arithmetic operations, if any operation results in an illegal value, an arithmetic exception occurs at runtime. In Python, ArithmeticError represents this exception and serves as the base class for all errors that occur during arithmetic operations, such as division by zero, overflow, or floating-point errors.
Basic Exception Handling with try-except
You can use a try-except block to catch ArithmeticError and handle errors gracefully ?
try:
result = 10 / 0
except ArithmeticError:
print("ArithmeticError caught: division by zero.")
ArithmeticError caught: division by zero.
Capturing Exception Details
Use the as keyword to capture the exception object and access error details ?
try:
result = 5 / 0
except ArithmeticError as e:
print(f"Caught ArithmeticError: {e}")
print(f"Exception type: {type(e).__name__}")
Caught ArithmeticError: division by zero Exception type: ZeroDivisionError
Handling Specific Arithmetic Exceptions
ArithmeticError includes several specific exceptions. You can handle them individually for more precise error handling ?
import math
def handle_arithmetic_operations():
operations = [
lambda: 10 / 0, # ZeroDivisionError
lambda: math.exp(1000), # OverflowError
lambda: float('inf') - float('inf') # May raise FloatingPointError
]
for i, operation in enumerate(operations):
try:
result = operation()
print(f"Operation {i+1} result: {result}")
except ZeroDivisionError:
print(f"Operation {i+1}: Division by zero detected")
except OverflowError:
print(f"Operation {i+1}: Number too large to represent")
except ArithmeticError as e:
print(f"Operation {i+1}: Other arithmetic error - {e}")
handle_arithmetic_operations()
Operation 1: Division by zero detected Operation 2: Number too large to represent Operation 3 result: nan
Using ArithmeticError as General Handler
Using ArithmeticError catches all arithmetic-related exceptions uniformly, simplifying error handling ?
import math
expressions = ["10 / 0", "2 ** 10000", "math.sqrt(-1)"]
for expr in expressions:
try:
result = eval(expr)
print(f"Result of '{expr}': {result}")
except ArithmeticError as e:
print(f"ArithmeticError in '{expr}': {type(e).__name__} - {e}")
except ValueError as e:
print(f"ValueError in '{expr}': {e}")
ArithmeticError in '10 / 0': ZeroDivisionError - division by zero Result of '2 ** 10000': (very large number) ValueError in 'math.sqrt(-1)': math domain error
Exception Hierarchy
Understanding the relationship between ArithmeticError and its subclasses helps in choosing the right exception handler ?
| Exception | Description | Common Cause |
|---|---|---|
ArithmeticError |
Base class for arithmetic errors | General arithmetic issues |
ZeroDivisionError |
Division or modulo by zero |
x / 0 or x % 0
|
OverflowError |
Result too large to represent | math.exp(1000) |
FloatingPointError |
Floating point operation failed | Platform-specific float errors |
Conclusion
Use ArithmeticError to catch all arithmetic-related exceptions uniformly, or handle specific exceptions like ZeroDivisionError individually for more precise error handling. This approach ensures your programs handle mathematical errors gracefully and continue execution.
