Best possible method of error handling of clock class?

102 views Asked by At

I want the code to stop working and return that the input time(hour) etc. is invalid as it is not between 1-24. However due to str statement of the class the invalid time still prints out. Is there anyway to show error without printing out the invalid time. I tried using try/except and assert to give error.

class clock():  
 def __init__(self,hour, minute, second):
   self.hour=hour
   self.minute=minute
   self.second=second
 def __str__(self):
  return str (self.hour)+":" + str(self.minute)+":"+str(self.second)
2

There are 2 answers

0
Jean-Paul Calderone On BEST ANSWER

Don't ever allow invalid states to exist.

class Clock():  
   def __init__(self, hour, minute, second):
       if not (0 <= hour < 24 and 0 <= minute < 60 and 0 <= second < 60):
           raise ValueError("Clock values out of bounds")
       self.hour = hour
       self.minute = minute
       self.second = second
0
Noctis Skytower On

The accepted answer is good but could be improved a little with better error messages:

class Clock:
    def __init__(self, hour, minute, second):
        if hour not in range(24):
            raise ValueError('hour not in range(24)')
        if minute not in range(60):
            raise ValueError('minute not in range(60)')
        if second not in range(60):
            raise ValueError('second not in range(60)')
        self.__hour = hour
        self.__minute = minute
        self.__second = second

    def __str__(self):
        return f'{self.__hour}:{self.__minute}:{self.__second}'

Whenever the Clock class is used incorrectly, the ValueError will state exactly what went wrong.