Python try except block doesn't raise correct error

39 Views Asked by At

I have the following code:

num2hgh = Exception
txt = 'enter your grade '
while True:
    try:
        grade = int(input(txt))
        print(grade)
        if grade > 100:
            raise num2hgh
    except num2hgh:
        txt = 'Grade to high, enter again: '
    except ValueError:
        txt = 'Please enter an integer; '
    else:
        break

when I enter abc I don't get a ValueError I keep getting a num2hgh error. Why? (I've been searching the internet and can't find an example)

1

There are 1 best solutions below

0
Köksal kotan On BEST ANSWER

Because there is already a ValueError in Exeption in num2hgh, according to the order of operations, since there is a ValueError in Exeption, it exits from there.

If you fix the code like this it will work

​

num2hgh = Exception
txt = 'enter your grade '
while True:
    try:
        grade = int(input(txt))
        print(grade)
        if grade > 2:
            raise num2hgh
    except ValueError:
        txt = 'Please enter an integer; '
    except num2hgh:
        txt = 'Grade to high, enter again: '
    else:
        break