Skip to the next iteration if a warning is raised

Question:

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

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.

Asked By: Macosso

||

Answers:

Instead of using warn function throw a warning object that except will detect.

CODE:

import warnings

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

for i in range(10):
    try:
        # code that may raise a warning
        k = my_func(i)
    except Warning:
        continue
    print(i, " : ",k) 

OUTPUT:

0 : No Problem
2 : No Problem
4 : No Problem
6 : No Problem
8 : No Problem
Answered By: Avad

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)
Answered By: 12944qwerty
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.