Rixy
Rixy

Reputation: 49

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)

Upvotes: 1

Views: 2641

Answers (2)

Flavio Adamo
Flavio Adamo

Reputation: 389

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)

Upvotes: 4

Matheus
Matheus

Reputation: 101

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

Upvotes: 1

Related Questions