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

时间:2018-04-27 22:27:52

标签: python python-3.x datetime if-statement 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)))

提前谢谢

2 个答案:

答案 0 :(得分:3)

你很亲密。诀窍是使用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)))

答案 1 :(得分:0)

使用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]