1

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.

Macosso
  • 1,352
  • 5
  • 22
  • 1
    You need to use [warning filters](https://docs.python.org/3/library/warnings.html#warning-filter) to turn warnings into exceptions. – Barmar Feb 13 '23 at 16:16

2 Answers2

2

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)
12944qwerty
  • 2,001
  • 1
  • 10
  • 30
  • ``` 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. think using ```warnings.simplefilter("error")``` is the appropriate solution – Macosso Feb 13 '23 at 16:29
1

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
Avad
  • 197
  • 1
  • 8