0

"You should throw an exception that matches the class name." Previously I had made a Date class and a Time class. They each throw InvalidDateException and InvalidTimeException and also work as intended. Currently they are part of a project with classes including Patient, Doctor, etc. These are an extension of an abstract Patient class. Each of these classes needs to only throw exceptions matching their class name. For example, a Patient object is instantiated or set to have an empty firstName, or a dateOfBirth that does not exist. It should throw InvalidPatientException and not InvalidDateException or InvalidPersonException.

This is output from the Patient class. It works as intended but I need to have only InvalidPatientExceptions

This does not do anything more than my Date class already does. Patient still gives an InvalidDateException

public void setDOB(String dateOfBirth) throws InvalidPersonException {
  try{
    Date date=new Date(dateOfBirth);
    this.dateOfBirth=date.getDate();
  }
  catch(InvalidDateException x) {
    throw new InvalidPersonException("Invalid Date of Birth: <"+dateOfBirth+"- ");
  }

Any knowledge about what I am trying to do or a reference would help. I'm new to exceptions.

  • 4
    *You should throw an exception that matches the class name*: no, you shouldn't. You should throw the best exception describing the problem. In your snippet, it should be an IllegalArgumentException (or better, the argument should be of type LocalDate, and it shouldn't throw any exception). – JB Nizet Sep 30 '18 at 10:09
  • Is this `Date` class `java.util.Date`? I really hope not. *Don't* use `java.util.Date` to model a date of birth, despite the name it models an *instant* in time, which will be a different "calendar date" depending upon the time zone of the JVM. Additionally, `date.getDate()` would then be giving you the day of the month on which the patient is born. Use `java.time.LocalDate`. – Andy Turner Sep 30 '18 at 10:17
  • I included the quote "You should throw an exception that matches the class name" because this is the instructors response to questions asked on a class discussion. I have asked a friend and older brother with more experience than me. They both say that what I am being told to do doesn't make sense. Can I not use the same methods in my Date or Person class that try/catch/if/throw exceptions to print errors for my other classes that use them? – Brett Hasbrouck Sep 30 '18 at 10:19
  • No. None of these are java.util classes. Date and Time are classes made by me that work as they should for the rest of my project. – Brett Hasbrouck Sep 30 '18 at 10:20

0 Answers0