Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Skip to the next iteration if a warning is raised

How can I skip the iteration if warning is raised

Suppose I have the code below

import warnings

# The function that might raise a warning
def my_func(x):
    if x % 2 != 0:
        warnings.warn("This is a warning")
        return "Problem"     
    else:
        return "No Problem"
        

for i in range(10):
    try:
        # code that may raise a warning
        k = my_func(i)
    except Warning:
        # skip to the next iteration if a warning is raised
        continue
        
    # rest of the code
    print(i, " : ",k) # Only print this if warning was not raised in try:except

I would expect this to print only even numbers as my_funct(i) will raise a warning for odd numbers

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

update:

my_func(i) was used just for illustration purposes, the actual problem I want to use might not have an obvious returned value that raises a warning.

>Solution :

Warnings don’t throw an exception by default.
You can specify warnings to throw an exception.
Just run this right after the import

warnings.simplefilter("error")

Or, you can just check the result of the function. Check if the result was "Problem" or "No Problem".

for i in range(10):
    k = my_func(i)
    if k == "Problem":
        continue
        
    # rest of the code
    print(i, " : ",k)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading