Fix Python – In Python, how does one catch warnings as if they were exceptions?

Question

Asked By – Boris Gorelik

A third-party library (written in C) that I use in my python code is issuing warnings. I want to be able to use the try except syntax to properly handle these warnings. Is there a way to do this?

Now we will see solution for issue: In Python, how does one catch warnings as if they were exceptions?


Answer

To handle warnings as errors simply use this:

import warnings
warnings.filterwarnings("error")

After this you will be able to catch warnings same as errors, e.g. this will work:

try:
    some_heavy_calculations()
except RuntimeWarning:
    breakpoint()

P.S. Added this answer because the best answer in comments contains misspelling: filterwarnigns instead of filterwarnings.

This question is answered By – niekas

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0