简体   繁体   中英

ValueError not caught in exception

I am executing the below code to catch input that is not a number or the number not within the range. i could catch the assertionerror but not the value error. can someone help me understand why i am not catching the valueerror?

What i am trying to do: i am getting the input from the user to see whether x is a number and it falls within the range specified that is min and max. if the input fails the validation, i should request the user to input the value again until the validation is passed so: when x = <<string>> , i should get "Enter a valid int" message. When x not within range, i should get "Enter a number between -10 and 10" .

def readint(x,min,max):
    try:
        #x=int(input("Enter number betwen min and max: "))
        assert (x<=max and x>=-min)
    except ValueError:
         print("Enter a valid int")
    except AssertionError:
        print("Enter a number between -10 and 10")
        
    except NameError:
        print("Enter a valid int")


while True:
    readint(x=int(input("Enter number betwen min and max: ")),min=-10,max=10)

You will get ValueError when a conversion from str to int fails. I modified your program, so the error is thrown within the try / except block:

def readint(low, high):
    try:
        x = int(input(f"Enter number betwen {low} and {high}, inclusive: "))
        assert (low <= x and x <= high)
    except ValueError:
         print("Enter a valid int")
    except AssertionError:
        print(f"Enter a number between {low} and {high}, inclusive")
    except NameError:
        print("Enter a valid int")

while True:
    readint(-10, 10)

The following is from running the above code:

Enter number betwen min and max: 1
Enter number betwen min and max: 22
Enter a number between -10 and 10
Enter number betwen min and max: -1
Enter number betwen min and max: -22
Enter a number between -10 and 10
Enter number betwen min and max: asdf
Enter a valid int

When I entered asdf that blew up the conversion to integer, and a ValueError was thrown, so we see "Enter a valid int".

The answer is:

def readint( min, max):
    while True:
        try:
            x = int(input("Please enter a number: "))
            assert (x<=max and x>=min)
            return x
            break
        except ValueError:
            print("Enter a valid int")
        except AssertionError:
            print("Enter a number between -10 and 10")
    
        except NameError: 
            print("Enter a valid int")
#

v = readint( -10, 10)
print("The number is:", v)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM