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?