-1

I should check if the values entered while creating the object are incorrect,for example invalid dates like 30.02.2021 in date object. I want to give an error message and close the program using the exit () command, should i do the value checks in the constructor or after the object is created?

public Date(int day, int month, int year) {
    if(check(day,month,year)) {
    this.day = day;
    this.month = month;
    this.year = year;
    }
    else {
        System.out.println("Error:Invalid Date!,Please check input file and try again!");
        System.exit(1); 
    }
}

1 Answers1

4

Well, In real life you won't exit the application when the 'Date' object could not be created because of wrong argument, that's for sure.

In other words, the decision to exit the application is beyond the scope/responsibility of the code of "Date" object.

Now, in java you have an exception mechanism: you can check for parameters in the constructor and throw, say, IllegalArgumentException if some parameter is wrong.

When the exception is thrown, the whole "flow" (thread if you've already learned about that) will "pop" till someone will catch the exception.

You could catch the exception in the "main" class or in any other "right place" and then make a decision whether to exit the application, to "log" the error and continue execution, etc. The point is that the decision of "what to do (how to handle the exception)" is decoupled from the point in code where you check the input.

If you have any doubts about throwing exceptions from constructors read this link

Mark Bramnik
  • 39,963
  • 4
  • 57
  • 97