import warnings
warnings.warn("Warning...........Message")

See the python documentation: here

Answer from necromancer on Stack Overflow
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ library โ€บ warnings.html
Warning control โ€” Python 3.14.3 documentation
January 29, 2026 - In -W and PYTHONWARNINGS, module is a literal string that the fully qualified module name must be equal to (case-sensitively), ignoring any whitespace at the start or end of module. lineno is an integer that the line number where the warning occurred must match, or 0 to match all line numbers. Since the Warning class is derived from the built-in Exception class, to turn a warning into an error we simply raise category(message).
๐ŸŒ
Reuven Lerner
lerner.co.il โ€บ home โ€บ blog โ€บ python โ€บ working with warnings in python (or: when is an exception not an exception?)
Working with warnings in Python (Or: When is an exception not an exception?) โ€” Reuven Lerner
May 12, 2020 - While theyโ€™re included along with the exception hierarchy, warnings are exceptions, but theyโ€™re neither raised nor used like normal exceptions. What are they, and how do we use them? First, some history: Warnings have been around in Python for quite some time, since Python 2.1 (back in the year 2000).
๐ŸŒ
Fabienmaussion
fabienmaussion.info โ€บ scientific_programming โ€บ week_06 โ€บ 01-Exceptions.html
Errors, Exceptions and Warnings โ€” Scientific Programming
Warning messages are typically issued in situations where it is useful to alert the user of some condition in a program, where that condition (normally) doesnโ€™t warrant raising an exception and terminating the program. For example, a library will issue a warning when a program uses an obsolete ...
๐ŸŒ
Devarea
devarea.com โ€บ python-exceptions-and-error-handlings
Python โ€“ Exceptions and Error Handlings โ€“ Developers Area
Exception handling is not error handling, you will not use exception for something you can check for example if you divide x/y , check that y is not zero using if statement and not using exceptions ยท In Python an exception can be thrown , it is represented by an object (a class derived from the Exception).
๐ŸŒ
Board Infinity
discuss.boardinfinity.com โ€บ programming language
What is the difference between Warnings and Exception in Python? - Programming Language - Discussion Forum | Board Infinity
September 28, 2022 - Warnings are provided to warn the ... programming elements, such as keyword, function or class, etc. A warning in a program is distinct from an error....
Find elsewhere
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ warnings-in-python
Warnings in Python - GeeksforGeeks
January 23, 2020 - Python warnings are non-fatal messages that alert the user to potential problems in the code. Unlike exceptions, warnings do not interrupt the execution of the program, but they notify the user that something might not be working as expected.
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ warning-control-in-python-programs
Warning control in Python Programs
Warning is different from error in a program. If error is encountered, Python program terminates instantly. Warning on the other hand is not fatal. It displays certain message but program continues. Warnings are issued to alert the user of certain conditions which aren't exactly exceptions.
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ library โ€บ exceptions.html
Built-in Exceptions โ€” Python 3.14.3 documentation
Enabling the Python Development Mode shows this warning. Added in version 3.2. The following are used when it is necessary to raise multiple unrelated exceptions. They are part of the exception hierarchy so they can be handled with except like all other exceptions.
๐ŸŒ
Towards Data Science
towardsdatascience.com โ€บ home โ€บ latest โ€บ the catcher in theโ€ฆ python. catch exceptions and warnings with one tool
The Catcher in the... Python. Catch Exceptions and Warnings with One Tool | Towards Data Science
January 24, 2025 - Python has some nice approach to handling exceptions. You can catch them, raise them, re-raise them, raise two exceptions at the same time (or rather, one exception from another), log them, and to create custom errors and their hierarchy, to name just the most important ones. If you want to handle warnings, you can also do that โ€“ but you need two separate tools: one for exceptions and one for warnings.
Top answer
1 of 6
268

It seems that your configuration is using the print option for numpy.seterr:

>>> import numpy as np
>>> np.array([1])/0   #'warn' mode
__main__:1: RuntimeWarning: divide by zero encountered in divide
array([0])
>>> np.seterr(all='print')
{'over': 'warn', 'divide': 'warn', 'invalid': 'warn', 'under': 'ignore'}
>>> np.array([1])/0   #'print' mode
Warning: divide by zero encountered in divide
array([0])

This means that the warning you see is not a real warning, but it's just some characters printed to stdout(see the documentation for seterr). If you want to catch it you can:

  1. Use numpy.seterr(all='raise') which will directly raise the exception. This however changes the behaviour of all the operations, so it's a pretty big change in behaviour.
  2. Use numpy.seterr(all='warn'), which will transform the printed warning in a real warning and you'll be able to use the above solution to localize this change in behaviour.

Once you actually have a warning, you can use the warnings module to control how the warnings should be treated:

>>> import warnings
>>> 
>>> warnings.filterwarnings('error')
>>> 
>>> try:
...     warnings.warn(Warning())
... except Warning:
...     print 'Warning was raised as an exception!'
... 
Warning was raised as an exception!

Read carefully the documentation for filterwarnings since it allows you to filter only the warning you want and has other options. I'd also consider looking at catch_warnings which is a context manager which automatically resets the original filterwarnings function:

>>> import warnings
>>> with warnings.catch_warnings():
...     warnings.filterwarnings('error')
...     try:
...         warnings.warn(Warning())
...     except Warning: print 'Raised!'
... 
Raised!
>>> try:
...     warnings.warn(Warning())
... except Warning: print 'Not raised!'
... 
__main__:2: Warning: 
2 of 6
75

To add a little to @Bakuriu's answer:

If you already know where the warning is likely to occur then it's often cleaner to use the numpy.errstate context manager, rather than numpy.seterr which treats all subsequent warnings of the same type the same regardless of where they occur within your code:

import numpy as np

a = np.r_[1.]
with np.errstate(divide='raise'):
    try:
        a / 0   # this gets caught and handled as an exception
    except FloatingPointError:
        print('oh no!')
a / 0           # this prints a RuntimeWarning as usual

Edit:

In my original example I had a = np.r_[0], but apparently there was a change in numpy's behaviour such that division-by-zero is handled differently in cases where the numerator is all-zeros. For example, in numpy 1.16.4:

all_zeros = np.array([0., 0.])
not_all_zeros = np.array([1., 0.])

with np.errstate(divide='raise'):
    not_all_zeros / 0.  # Raises FloatingPointError

with np.errstate(divide='raise'):
    all_zeros / 0.  # No exception raised

with np.errstate(invalid='raise'):
    all_zeros / 0.  # Raises FloatingPointError

The corresponding warning messages are also different: 1. / 0. is logged as RuntimeWarning: divide by zero encountered in true_divide, whereas 0. / 0. is logged as RuntimeWarning: invalid value encountered in true_divide. I'm not sure why exactly this change was made, but I suspect it has to do with the fact that the result of 0. / 0. is not representable as a number (numpy returns a NaN in this case) whereas 1. / 0. and -1. / 0. return +Inf and -Inf respectively, per the IEE 754 standard.

If you want to catch both types of error you can always pass np.errstate(divide='raise', invalid='raise'), or all='raise' if you want to raise an exception on any kind of floating point error.

๐ŸŒ
LabEx
labex.io โ€บ tutorials โ€บ python-how-to-capture-python-runtime-warnings-425664
How to capture Python runtime warnings | LabEx
Python warnings are messages that indicate potential issues or problematic code patterns without stopping the program's execution. Unlike exceptions, warnings allow the script to continue running while alerting developers to potential problems.
๐ŸŒ
Readthedocs
jython.readthedocs.io โ€บ en โ€บ latest โ€บ ExceptionHandlingDebug
Chapter 7: Exception Handling and Debugging โ€” Definitive Guide to Jython latest documentation
Warnings are easy to define, but they can be complex if you wish to define rules on them using filters. Much like exceptions, there are a number of defined warnings that can be used for categorizing. In order to allow these warnings to be easily converted into exceptions, they are all instances of the Exception type. Table 5-2. Python Warning Categories
๐ŸŒ
Travisbriggs
garden.travisbriggs.com โ€บ garden โ€บ warnings-python
How to squash warnings in Python by elevating them to errors โ€ข Digital Garden of Travis Briggs
November 29, 2022 - Python has a great Exception handling system. It also has a lesser used but still important system of "warnings", which are like Exceptions except they are intended when a "condition (normally) doesnโ€™t warrant raising an exception and terminating the program".
๐ŸŒ
Real Python
realpython.com โ€บ python-raise-exception
Python's raise: Effectively Raising Exceptions in Your Code โ€“ Real Python
January 25, 2025 - If you decide to use custom exceptions, then remember that the naming conventions for classes apply. Additionally, you should add the suffix Error to custom exceptions that represent errors and no suffix for non-error exceptions. If youโ€™re defining custom warnings, then you should use the Warning suffix instead.