![]() |
VOOZH | about |
Arithmetic errors in Python are common and occur when mathematical operations fail to execute properly. These errors can be caused by various issues, such as invalid input, division by zero, or exceeding number limits. Understanding the causes and how to handle these errors is important for writing robust Python programs.
Output
Hangup (SIGHUP)
Traceback (most recent call last):
File "/home/guest/sandbox/Solution.py", line 3, in <module>
res = a / b # Raises ZeroDivisionError
~~^~~
ZeroDivisionError: division by zero
In this article, we'll explore common types of arithmetic errors, their causes and how to handle them.
An OverflowError occurs when a number exceeds the maximum limit that Python's data types can represent, typically in cases of large numbers, recursion or exponentiation. For Example:
Output
Hangup (SIGHUP)
Traceback (most recent call last):
File "/home/guest/sandbox/Solution.py", line 2, in <module>
print(a)
~~~~~^^^
ValueError: Exceeds the limit (4300 digits) for integer string conversion; use sys.set_int_max_str_digits() to increase the limit
To handle an OverflowError, break calculations into smaller parts or use data types like Python's decimal module for high-precision arithmetic.
1.000000000000000000000000000E+10000
ValueError occurs when an invalid operation is performed on incompatible data types, such as adding a string to an integer.
Output
Hangup (SIGHUP)
Traceback (most recent call last):
File "/home/guest/sandbox/Solution.py", line 3, in <module>
res = a + b # Raises ValueError because num1 is a string
~~^~~
TypeError: can only concatenate str (not "int") to str
To handle a ValueError, ensure values are of the correct data type before performing operations, and use exception handling to catch and manage errors gracefully.
15
TypeError occurs when performing arithmetic operations on incompatible data types, such as adding a list and a number.
Output
Hangup (SIGHUP)
Traceback (most recent call last):
File "/home/guest/sandbox/Solution.py", line 3, in <module>
res = a + b # Raises TypeError because a list and integer can't be added
~~^~~
TypeError: can only concatenate list (not "int") to list
To handle a TypeError, ensure operands are of the correct type before operations, and use type checking or try-except blocks to manage errors.
Both operands must be integers.
FloatingPointError occurs when floating-point arithmetic results in precision issues leading to unexpected outcomes, especially in operations like comparisons.
False
To handle a FloatingPointError, use the math.isclose() function to check for approximate equality of floating-point numbers.
The numbers are approximately equal.