Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
custom exception
#1
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
Reply
#2
(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.
« We can solve any problem by introducing an extra level of indirection »
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  looking for a custom exception JarredAwesome 5 3,263 Sep-21-2020, 06:38 PM
Last Post: JarredAwesome
  problem using custom exception handling in python srm 3 3,068 Jul-03-2019, 09:10 PM
Last Post: ichabod801
  During handling of the above exception, another exception occurred Skaperen 7 26,920 Dec-21-2018, 10:58 AM
Last Post: Gribouillis

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020