How to catch a NumPy warning like an exception in Python
Last Updated :
28 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)
Output:

Using 'numpy.seterr' Function
The 'numpy.seterr' function to configure how NumPy handles warnings. NumPy warnings are typically emitted when there are issues related to numerical operations, data types, or other conditions that might lead to unexpected behavior. By configuring NumPy to treat warnings as exceptions, you can catch and handle them in your code. In the example above, np.seterr(all='raise') is used to configure NumPy to raise exceptions for all warnings. You can customize this behavior by specifying specific warning categories using the divide, over, under, etc., options of np.seterr based on your needs.
Python3
import numpy as np
# Configure NumPy to treat warnings as exceptions
np.seterr(all='raise')
# This will raise exceptions for all warnings
try:
# Code that might trigger a NumPy warning
# For example, performing an invalid operation
result = np.array([0, 1]) / 0
except Warning as e:
print(f"Caught a NumPy warning: {e}")
except Exception as e:
print(f"Caught an exception: {e}")
Output:
Conclusion
It is a matter of disappointment to see the errors or warnings while coding, but the various ways explained in this article will help you to catch the numpy warnings and resolve them or raise an exception, wherever required.
Similar Reads
How to create an empty matrix with NumPy in Python? In Python, an empty matrix is a matrix that has no rows and no columns. NumPy, a powerful library for numerical computing, provides various methods to create matrices with specific properties, such as uninitialized values, zeros, NaNs, or ones. Below are different ways to create an empty or predefin
3 min read
How to Catch Multiple Exceptions in One Line in Python? There might be cases when we need to have exceptions in a single line. In this article, we will learn about how we can have multiple exceptions in a single line. We use this method to make code more readable and less complex. Also, it will help us follow the DRY (Don't repeat code) code method.Gener
2 min read
How to pass argument to an Exception in Python? There might arise a situation where there is a need for additional information from an exception raised by Python. Python has two types of exceptions namely, Built-In Exceptions and User-Defined Exceptions.Why use Argument in Exceptions? Using arguments for Exceptions in Python is useful for the fol
2 min read
How to Ignore an Exception and Proceed in Python There are a lot of times when in order to prototype fast, we need to ignore a few exceptions to get to the final result and then fix them later. In this article, we will see how we can ignore an exception in Python and proceed. Demonstrate Exception in Python Before seeing the method to solve it, l
3 min read
How to Throw a Custom Exception in Kotlin? In addition to the built-in Exception Classes, you can create your own type of Exception that reflects your own cause of the exception. And you will appreciate the use of Custom Exception when you have multiple catch blocks for your try expression and can differentiate the custom exception from regu
2 min read
Catch and Throw Exception In Ruby An exception is an object of class Exception or a child of that class. Exceptions occurs when the program reaches a state in its execution that's not defined. Now the program does not know what to do so it raises an exception. This can be done automatically by Ruby or manually. Catch and Throw is si
3 min read
How to log a Python exception? To log an exception in Python we can use a logging module and through that, we can log the error. The logging module provides a set of functions for simple logging and the following purposes DEBUGINFOWARNINGERRORCRITICALLog a Python Exception Examples Example 1:Logging an exception in Python with an
2 min read
How to handle a Python Exception in a List Comprehension? In Python, there are no special built-in methods to handle exceptions in the list comprehensions. However, exceptions can be managed using helper functions, try-except blocks or custom exception handling. Below are examples of how to handle common exceptions during list comprehension operations:Hand
3 min read
How to Create Array of zeros using Numpy in Python numpy.zeros() function is the primary method for creating an array of zeros in NumPy. It requires the shape of the array as an argument, which can be a single integer for a one-dimensional array or a tuple for multi-dimensional arrays. This method is significant because it provides a fast and memory
4 min read
Python | Reraise the Last Exception and Issue Warning Problem - Reraising the exception, that has been caught in the except block. Code #1: Using raise statement all by itself. Python3 1== def example(): try: int('N/A') except ValueError: print("Didn't work") raise example() Output : Didn't work Traceback (most recent call last): File "", lin
2 min read