0

I need to make a program that initializing class objects throw an exception if the day, month, and year passed as arguments to initialize object variables do not represent a valid date. The exception may only issue an invalid date message.

I do not get much exception in Python, so I did an algorithm that only has an if and else that checks whether it is valid or not. How to transform according to what I need, ie: an exception if the day, month, and year passed as arguments to initialize object variables do not represent a valid date?

def dois(day, month, year):
    checks = "true"
    i = 0
    while checks == "true" and i == 0:
        if (year%4 == 0 and year%100!= 0) or year%400 == 0:
            leap_year = "sim"
        else:
            leap_year = "nao"

        if month < 1 or month > 12:
            checks = "false"

        if day > 31 or ((month == 4 or month == 6 or month == 9 or month == 11) and day > 30):
            checks = "false"

        if (month == 2 and leap_year == "nao" and day > 28) or ( month == 2 and leap_year == "sim" and day > 29):
            checks = "false"
        i = i + 1

    if checks == "true":
        print("Valid date")
    else:
        print("Invalid date")

I can not use ready-made functions like time.strptime, I need to use what I have implemented

2
  • 2
    How academic does this need to be…? In practice you'd do datetime.datetime(year, month, day) and let it raise an exception. Commented Dec 6, 2017 at 12:26
  • 1
    Why the while?! It's only ever doing one iteration of that anyway. Commented Dec 6, 2017 at 12:28

2 Answers 2

2

The practical answer:

import datetime

try:
    datetime.date(year, month, day)
    print('Valid date')
except ValueError:
    raise ValueError('Invalid date')

The try..except..raise is really just to satisfy the condition that "the exception may only issue an invalid date message" (whatever that means exactly). In practice you would just use the ValueError raised by date as is. I don't know what the point if this exercise is, whether converting an exception or reinventing date parsing is the idea.

Sign up to request clarification or add additional context in comments.

Comments

0
# declare a new exception class
class ValidationException(Exception):
    pass

# later
if checks != "true":
    raise ValidationException("Invalid data")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.