How to catch a NumPy warning like an exception in Python
Last Updated :
24 Apr, 2025
An N-dimensional array that is used in linear algebra is called NumPy. Whenever the user tries to perform some action that is impossible or tries to capture an item that doesn't exist, NumPy usually throws an error, like it's an exception. Similarly, in a Numpy array, when the user tries to perform some action that is impossible or tries to capture the item that doesn't exist, such as dividing by zero, it throws an exception. In this article, we will study various ways to catch Numpy warnings like it's an exception.
Catch a NumPy Warning like an Exception in Python
- Using errstate() function
- Using warnings library
Using errstate() Function
The Numpy context manager which is used for floating point error handling is called errstate() function. In this way, we will see how we can catch Numpy errors using errstate() function.
Syntax: with numpy.errstate(invalid='raise'):
Example 1: In this example, we have specified a Numpy array, which we try to divide by zero and catch the error using errstate() function. It raises the error stating 'FloatingPointError' which we caught and printed our message.
Python3
# Import the numpy library
import numpy as np
# Create a numpy array
arr = np.array([1,5,4])
# Divide by Zero Exception
with np.errstate(invalid='raise'):
try:
arr / 0
except FloatingPointError:
print('Error: Division by Zero')
Output:

Using warnings library
The message shown to user wherever it is crucial, whether the program is running or has stopped is called warning. In this way, we will see how we can catch the numpy warning using warnings library.
Syntax: with warnings.catch_warnings():
Example 1: In this example, we have specified a numpy array, which we try to divide by zero and print the error message using warnings library. It raises the error stating 'FloatingPointError' with detailed message of divide by zero encountered in divide.
Python3
# Import the numpy library
import numpy as np
# Create a numpy array
arr = np.array([1,5,4])
# Divide by zero Exception
with warnings.catch_warnings():
try:
answer = arr / 0
except Warning as e:
print('error found:', e)