Python Forum
custom exception - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: custom exception (/thread-41616.html)



custom exception - dcr - Feb-17-2024

I always get a nun2hgh error even when I input abc. What am I doing wrong?

Just figured it out. num2hgh is an exception so it's get's executed before ValueError. Change the order and it works


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



RE: custom exception - Gribouillis - Feb-17-2024

(Feb-17-2024, 08:03 PM)dcr Wrote: num2hgh is an exception so it's get's executed before ValueError. Change the order and it works
In this code, num2hgh is just the Exception type. If you catch it, it will also catch other exceptions such as ValueError. It is better to define your own exception type
class GradeOverflow(Exception):
    pass
txt = 'enter your grade '
while True:
    try:
        grade = int(input(txt))
        print(grade)
        if grade > 100:
            raise GradeOverflow(grade)
    except GradeOverflow:
        txt = 'Grade to high, enter again: '
    except ValueError:
        txt = 'Please enter an integer; '
    else:
        break
Now the order does not matter anymore.