建议一种更好的方法来处理异常情况

时间:2014-11-09 17:36:33

标签: python-3.x exception-handling

我正在为班级做作业,我们把军事时间变成标准时间,并且认为我很聪明地有单独的函数来获取输入和检查输入 - 我的理由是如果check_input函数失败我可以继续循环通过get_inputs函数,直到用户以正确的格式输入它。

但是,当我输入像“jklfd”这样的乱码时,我的get_input函数崩溃了,因为它无法将其转换为属于该函数的列表。

在这种情况下,是否有更好的方法来处理异常?此外,任何一般提示或建议总是受到赞赏。在此先感谢您的帮助!

    __author__ = 'Ethan'
#This program takes input in military time in the format hour:minutes and outputs
#the time in standard time hour:minute AM/PM

def main():
    print_intro()
    while True:
        mil_h, m = get_inputs()
        if check_input(mil_h,m):
            break
    reformat_time(mil_h,m)

def print_intro():
    print("This program takes input as military time from user")
    print("in format hour:minute ex. 23:34")
    print("and outputs the time in standard AM/PM format")
    print("ex. from above 11:34 PM")

def get_inputs():
    raw = input("Enter time: ")
    time_list = raw.split(":")
    mil_h = int(time_list[0])
    m = int(time_list[1])
    return mil_h, m

def check_input(mil_h,m):
    try:
        if mil_h >= 24 or mil_h <0:
            print("Time must be in format hh:mm")
            print("Hour must be in range 0 to 23")
            return False
        elif m >= 60 or m <0:
            print("Time must be in format hh:mm")
            print("Minute must be in range 0 to 59")
            return False
        else:
            return True
    except:
        print("Input must be in military time in format hh:mm")

def reformat_time(mil_h,m):
    am_pm = "AM"
    if mil_h == 12:
        am_pm = "PM"
        stand_h = 12
    elif mil_h > 12:
        am_pm = "PM"
        stand_h = mil_h % 12
    else:
        stand_h = mil_h
    print(stand_h,':', m,' ', am_pm, sep='')

main()

1 个答案:

答案 0 :(得分:0)

在拆分字符串之前,请使用if语句

if(raw.contains(":")&& raw.length()>=3 && raw) {
list=raw.split(":")
//rest of code
} else { throw exception}

应该编辑异常代码,如下所示:

except:
println("Code must be in military format")
get_inputs()
//recall the check_input method for the values found in get_inputs
check_input()

通过这种方式,您可以知道raw格式正确,您可能希望为raw添加更多先决条件(例如确保它只包含数字),以便程序不会因不需要的输入而崩溃。 (对不起语法,我不明确知道python)