>>> import datetime >>> def validate(my_str_date): try: datetime.datetime.strptime(my_str_date, '%Y-%m-%d') except ValueError: raise ValueError("Incorrect data format, should be YYYY-MM-DD") >>> validate('2003-12-23') >>> validate('2003/12/23') Traceback (most recent call last): File "", line 1, in File " ", line 5, in validate ValueError: "Incorrect data format, should be YYYY-MM-DD"
Here is what the above code is Doing:
1. We’ve defined a function called validate that takes a string as an argument.
2. We’ve used a try/except block to catch any ValueError exceptions.
3. We’ve used the datetime.datetime.strptime() method to parse the string into a datetime object.
4. If the string cannot be parsed into a datetime object, a ValueError exception is raised.
5. We’ve handled this exception by printing a message to the user.
You can use this same technique to handle any type of exception.