Home > Mobile >  How to pass the exception in for loop
How to pass the exception in for loop

Time:01-20

a = [2,"cat",None,1]

try:
    for i in a:
        print(int(i))
except Exception as e:
    print(e)
    pass

How to pass the exception in for loop. I need to put for loop inside try and need to pass the value in exception and get the value 1 from the list

CodePudding user response:

You can modify the code as follows to pass the exception in the for loop and still get the value 1 from the list:

a = [2,"cat",None,1]

for i in a:
    try:
        print(int(i))
    except Exception as e:
        print(e)
        pass

This way, the try block will be inside the for loop, and the except block will handle any exceptions that are raised when trying to convert the current element i to an integer. If an exception is raised, the pass statement will be executed, allowing the loop to continue to the next iteration, without stopping the whole loop.

An alternative way would be to use a list comprehension and filter out the elements that can't be converted to int.

a = [2,"cat",None,1]

valid_list = [i for i in a if isinstance(i, (int,float))]
print(valid_list)

This way, the final list will only contain the values that were successfully casted to int and the non-int values will be filtered out.

  • Related