自定义异常 - python3

时间:2018-04-26 03:11:20

标签: python-3.x exception

我试图通过使用将处理用户输入的类来创建自定义异常,这些类不在我希望他们输入的值的适当范围内(例如百分比标记必须介于0和100之间),但是,我不知道自己做错了什么。这是我的代码。感谢

import time
loc = [x, y]
safe_rect = ( x , y , w , h   )
# Time variables
time = time.time()
time_wanted = time + 3  # 3 seconds after the time is assigned to time

while True:
    if loc[0] >= safe_rect[0] and 
       loc[0] < safe_rect[0] + safe_rect[2] and
       loc[1] >= safe_rect[1] and
       loc[1] < safe_rect[1] + safe_rect[3]:
        if time.time() > time_wanted:
            not_yet_existent_do_something_function()

1 个答案:

答案 0 :(得分:0)

一些修正,但请参阅我的内联评论:

class IllegalMark(Exception): # use CamelCase and name meaningfully
    pass

while True:
    try:
        mark = int(input("Enter a mark between 0-100 to test validity: "))
        if mark not in range(0, 101):
            raise IllegalMark
            # break # don't need this since you call 'raise'
    except IllegalMark:
        print("Invalid mark")
        break # if you want to end on invalid, otherwise leave out