0

I have already checked this post and this post but their answers didn't work with my question. I have a function that checks if the date string taken from the user is valid and if not then the self created exception catches it:

import time

class MyException(Exception):
   
    def __init__(self, expression):
        self.expression = expression


    def __str__(self):
        return f'{self.expression} is not in the range 1-12.'


def my_fun(date_string):

    try:
        d = time.strptime(date_string, "%d/%m/%Y")
        if not (1 <= int(d[1]) <= 12):
            raise MyException(d[1]) from None

    except MyException as e:
        print(e)

As I am using 'time.strptime' before the if statement, when the invalid date like 02/14/2020 is passed to the function, the python itself catches ValueError exception with the message:

"time data '02/14/2020' does not match format '%d/%m/%Y'"

and doesn't let MyException to catch the exception although I am using from None according to this post. How do I fix it?

Coder
  • 431
  • 4
  • 11
  • @TomKarzes Thanks. I removed pass. The reason is I try to display a message that that tells the user which part of the date is wrong e.g. if the month is entered as 14 then it is out of range 1-12. – Coder Oct 29 '20 at 21:39
  • 1
    You have a chicken-and-egg problem. Essentially your code is attempting to use the results of a `strptime()` call that failed, so there's no `d` to reference — so it's impossible. – martineau Oct 29 '20 at 21:39
  • @martineau And I don't think there's any way to take the month or day from the date string, other than `time.strptime(date_string, "%d/%m/%Y")`, right? – Coder Oct 29 '20 at 21:42
  • 2
    You could parse the string manually using the `re` regular expression (RegEx) module, or some other way. There are third-party modules available that might be helpful. A popular one is named [dateutil](https://pypi.org/project/python-dateutil/). – martineau Oct 29 '20 at 21:48
  • @martineau Thanks. – Coder Oct 29 '20 at 21:50

0 Answers0