How to use raise ValueError?

1.9k Views Asked by At

I want to see ValueError 4 times but it is showing once, why the program cutting to search the other double numbers?

def isitDoubleorSingle(value):
    if(value%2!=0):
        raise ValueError("Number isn't double")
    print(value)    

list=[10,22,79,43,11,80]

for x in list:
    isitDoubleorSingle(x)
2

There are 2 best solutions below

0
Flavio Adamo On BEST ANSWER

This will solve your problem. You have to catch your Error in the except block or your script will stop running at your first raise ValueError()

edit: As @Nin17 said, you shouldn't redefine the built-in list, so renaming the list in my_list(or any name you want) should be better.

def isitDoubleorSingle(value):
    try:
        if(value%2!=0):
            raise ValueError()
    except ValueError:
            print(f"Number {value} isn't double")

my_list=[10,22,79,43,11,80]

for x in my_list:
    isitDoubleorSingle(x)
0
Matheus Simão Caixeta On

When you raise an exception, the program is already closed automatically, so it is not possible to display the ValueError more than once