【问题标题】:suggest a better way to handle exception in case建议一种更好的方法来处理异常以防万一
【发布时间】:2014-11-09 17:36:32
【问题描述】:

我正在为我们将军事时间转换为标准时间的课程做作业,并认为我会很聪明地拥有单独的函数来获取输入和检查输入 - 我的理由是如果 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()

【问题讨论】:

    标签: python-3.x exception-handling


    【解决方案1】:

    在拆分字符串之前使用 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)

    【讨论】:

    • 感谢您的回复。如果我走那条路,如果他们的输入未通过测试,我将如何返回并再次要求用户输入?
    • 使用 while 循环和布尔变量来跟踪成功
    猜你喜欢
    • 2015-09-09
    • 2015-09-25
    • 1970-01-01
    • 2018-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多