An error or exception is an unexpected event that occurs during program execution. It affects the flow of the program instructions which can terminate the program abnormally.
Responding or handling exceptions is called Exception Handling.
NumPy provides various ways to handle exceptions that occur during array operations.
Handle Floating-Point Errors in NumPy
In NumPy, the seterr()
function sets the way floating-point errors are handled.
It takes several parameters:
divide
: specifies the behavior for division by zero or infinityover
: specifies the behavior for floating-point overflowunder
: specifies the behavior for floating-point underflowinvalid
: specifies the behavior for invalid floating-point operations such as 0/0, inf-inf, and sqrt(-1)
Note: Possible values of all these parameters are "ignore"
, "warn"
, "raise"
, or "call"
. The default behavior for all types of errors is "warn"
.
Example 1: NumPy seterr() Function
import numpy as np
# set behavior for division by zero to 'raise'
np.seterr(divide='raise')
# divide array1 by array2
array1 = np.array([1, 2, 3])
array2 = np.array([0, 2, 0])
result = np.divide(array1, array2)
print(result)
Output
FloatingPointError: divide by zero encountered in true_divide
In this example, we have set the behavior for division by zero errors to raise
using np.seterr(divide='raise')
.
This means when np.divide()
encounters division by zero during the calculation, it will raise the FloatingPointError
error.
If we had set the behavior for division by zero to
divide='ignore'
- it doesn't raise an error or print a warning message and the output would be[inf 1. inf]
divide='warn'
- it prints a warning message and also runs the program and the output would be[inf 1. inf]
Example 2: The over Parameter in NumPy seterr() Function
import numpy as np
# set behavior for floating-point overflow to 'raise'
np.seterr(over='raise')
calc1 = np.exp(1000)
print(calc1)
Output
FloatingPointError: overflow encountered in exp
In the above example, we set the behavior for floating-point overflow to raise
.
We then calculated np.exp(1000)
, which results in a floating-point overflow because the result of the calculation is too large to be represented by the floating-point data type.
This raises an exception: FloatingPointError: overflow encountered in exp
.
Note: If we set np.seterr(under='raise')
and calculate np.exp(-1000)
, this raises an exception: FloatingPointError: underflow encountered in exp
.
Example 3: The invalid Parameter in NumPy seterr() Function
In Numpy, we can use the invalid
parameter in seterr()
to raise an exception when an invalid floating-point operation occurs. For example,
import numpy as np
# set the invalid parameter to 'raise'
np.seterr(invalid='raise')
# try taking the square root of a negative number
x = np.sqrt(-1)
# Output: FloatingPointError: invalid value encountered in sqrt
Here, we attempted to take the square root of -1, which is an invalid floating-point operation.
As we have set the invalid='raise'
, NumPy will raise a FloatingPointError
.
NumPy try-catch Block
We can use the try...except
block in NumPy to handle an error. Here's the syntax of try...except
:
try:
# code that may cause exception
except:
# code to run when exception occurs
Here, we have placed the code that could potentially raise an exception within the try
block. When an exception occurs in the try
block, it's caught by the except
block.
The try
and except
block must work together to handle the exception.
Let's see an example.
import numpy as np
array1 = np.array([1, 4, 3])
array2 = np.array([0, 2, 0])
# try to divide the arrays
try:
result = array1/array2
except ZeroDivisionError as e:
print("Error: Cannot divide by zero")
Output
runtimewarning: divide by zero encountered in divide