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 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 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
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
How to Print Exception Stack Trace in Python In Python, when an exception occurs, a stack trace provides details about the error, including the function call sequence, exact line and exception type. This helps in debugging and identifying issues quickly.Key Elements of a Stack Trace:Traceback of the most recent callLocation in the programLine
3 min read
Test if a function throws an exception in Python The unittest unit testing framework is used to validate that the code performs as designed. To achieve this, unittest supports some important methods in an object-oriented way: test fixturetest casetest suitetest runner A deeper insight for the above terms can be gained from https://www.geeksforgeek
4 min read
How to handle KeyError Exception in Python In this article, we will learn how to handle KeyError exceptions in Python programming language. What are Exceptions?It is an unwanted event, which occurs during the execution of the program and actually halts the normal flow of execution of the instructions.Exceptions are runtime errors because, th
3 min read
Python | Raising an Exception to Another Exception Let's consider a situation where we want to raise an exception in response to catching a different exception but want to include information about both exceptions in the traceback. To chain exceptions, use the raise from statement instead of a simple raise statement. This will give you information a
2 min read