Search code examples
pythonvalueerrorraise

How to use raise ValueError?


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)

Solution

  • 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)