Caique Fortunato
Caique Fortunato

Reputation: 55

Modifying program using exceptions in python

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

Upvotes: 0

Views: 41

Answers (2)

deceze
deceze

Reputation: 522125

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.

Upvotes: 2

vidstige
vidstige

Reputation: 13079

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

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

Upvotes: 0

Related Questions