Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catching specific error messages in try / except

I am new to python and I am about to make this new program that will ask you for your birthday. I've made some try/except clauses to avoid people entering info in strings or to high numbers. I would like my program to find out if the info entered equals a date in the end. If it does I would like to have it printed and if not I would like it to find out what part of the user input was wrong. I have therefore made some if clauses in the last except clause with the idea that the errors would equal a message.

I would like to know if it is possible to make the program match the messages with the error to find out the specific error and figure out what part of the input was wrong.

My code looks like this:

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)))
like image 242
SnitchingAuggie Avatar asked Apr 27 '18 22:04

SnitchingAuggie


People also ask

How do you catch an instance of a specific exception type?

Catching Specific Exceptions in Python A try clause can have any number of except clauses to handle different exceptions, however, only one will be executed in case an exception occurs. We can use a tuple of values to specify multiple exceptions in an except clause.

How do you catch error messages in Python?

message (at least in Python 2.7. 12). If you want to capture the error message, use str(e) , as in the other answers.

When an error occurs within a try clause?

If any exception occurs, the try clause will be skipped and except clause will run. If any exception occurs, but the except clause within the code doesn't handle it, it is passed on to the outer try statements. If the exception is left unhandled, then the execution stops.


1 Answers

You were close. The trick is to use ValueError as e and compare your strings against str(e). It's also good practice to use if / elif rather than repeated if statements.

Here's a working example:

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)))
like image 183
jpp Avatar answered Sep 29 '22 09:09

jpp