Search code examples
pythonpython-3.xclasserror-handlingpython-class

Best possible method of error handling of clock class?


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)

Solution

  • 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