繁体   English   中英

在 try / except 中捕获特定的错误消息

[英]Catching specific error messages in try / except

我是 python 的新手,我即将制作这个新程序,它会问你生日。 我做了一些 try/except 子句来避免人们以字符串或高数字输入信息。 我希望我的程序找出输入的信息最终是否等于日期。 如果是,我希望将其打印出来,如果没有,我希望它找出用户输入的哪一部分是错误的。 因此,我在最后一个 except 子句中创建了一些 if 子句,其想法是错误将等于一条消息。

我想知道是否有可能让程序将消息与错误进行匹配,以找出具体的错误并找出输入的哪一部分是错误的。

我的代码如下所示:

try: 
    print(datetime.date(int(birthYear), int(birthMonth), int(birthDay)))
except TypeError:
    if ValueError == "ValueError: month must be in 1..12": 
        print("Month " + str(birthMonth) + " is out of range. The month must be a number in 1...12")
    if ValueError == "ValueError: year " + str(birthYear) + " is out of range": 
        print("Year " + str(birthMonth) + " is out of range. The year must be a number in " + str(datetime.MINYEAR) + "..." + str(datetime.MAXYEAR))
    if ValueError == "ValueError: day is out of range for month": 
        print("Day " + str(birthDay) + " is out of range. The day must be a number in 1..." + str(calendar.monthrange(birthYear, birthMonth)))

你很接近。 诀窍是使用ValueError as e并将您的字符串与str(e)进行比较。 使用if / elif而不是重复的if语句也是一种很好的做法。

这是一个工作示例:

import calendar, datetime

try: 
    print(datetime.date(int(birthYear), int(birthMonth), int(birthDay)))
except ValueError as e:
    if str(e) == 'month must be in 1..12': 
        print('Month ' + str(birthMonth) + ' is out of range. The month must be a number in 1...12')
    elif str(e) == 'year {0} is out of range'.format(birthYear): 
        print('Year ' + str(birthMonth) + ' is out of range. The year must be a number in ' + str(datetime.MINYEAR) + '...' + str(datetime.MAXYEAR))
    elif str(e) == 'day is out of range for month': 
        print('Day ' + str(birthDay) + ' is out of range. The day must be a number in 1...' + str(calendar.monthrange(birthYear, birthMonth)))

使用 dict 以便您可以更轻松地添加

import calendar, datetime

birthYear= int(input('Birth year:'))
birthMonth= int(input('Birth month:'))
birthDay= int(input('Birth day:'))

error_dict = {
    'month must be in 1..12' : f'Month {birthMonth} is out of range. The month must be a number in 1...12',
     'year {0} is out of range':f'Year {birthMonth} is out of range. The year must be a number in  {datetime.MINYEAR} ...{datetime.MAXYEAR}',
    'day is out of range for month' : f'Day  {birthDay} is out of range. The day must be a number in 1... 12'
}
    
try: 
    print(datetime.date((birthYear), (birthMonth), (birthDay)))    
    
except ValueError as e:
    print(error_dict[str(e)])

输出

Birth year:32
Birth month:32
Birth day:32
Month 32 is out of range. The month must be a number in 1...12

[Program finished]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM