A part of my program checks the current data with a specified date to see if it is before that date. If it is, I want to throw a TooEarlyException
.
My TooEarlyException
class(note that it currently is checked, but I am trying to decide if it should be checked or unchecked):
public class TooEarlyException extends Exception {
private int dayDifference;
private String message = null;
public TooEarlyException(int dayDifference) {
this.dayDifference = dayDifference;
}
public TooEarlyException() {
super();
}
public TooEarlyException(String message) {
super(message);
this.message = message;
}
public TooEarlyException(Throwable cause) {
super(cause);
}
public int getDayDifference() {
return dayDifference;
}
@Override
public String toString() {
return message;
}
@Override
public String getMessage() {
return message;
}
}
Here is my code that checks the dates and throws the exception if necessary(assume that today
and dateSpecified
are Date
objects):
public void checkDate() throws TooEarlyException{
//Do Calendar and Date stuff to get required dates
...
//If current Date is greater than 4 weeks before the event
if(today.before(dateSpecified)) {
//Get difference of dates in milliseconds
long difInMs = dateSpecified.getTime() - today.getTime();
//Convert milliseconds to days(multiply by 8,640,000^-1 ms*s*min*h*days)
int dayDifference = (int)difInMs/8640000;
//Throw exception
throw new TooEarlyException(dayDifference);
} else { //Date restriction met
//Format date Strings
DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM);
System.out.printf("Today Date: %s%n", df.format(today));
System.out.printf("Event Date(Actual): %s%n", df.format(eventDateActual));
System.out.printf("Event Date(4 Weeks Prior): %s%n", df.format(dateSpecified));
}
}
How I call checkDate
:
try {
checkDate();
} catch(TooEarlyException e) {
System.out.printf("Need to wait %d days", e.getDayDifference());
e.printStackTrace();
System.exit(1);
}
Checked Exceptions should be used for predictable, but unpreventable errors that are reasonable to recover from.
My question with this is in my case, this error would be considered predictable but unpreventable, but not recoverable from, as my program needs to be run within 28 days of a specified date(this is because the API I am using has a restriction that in order to get data for an event, it must within 4 weeks before the event starts). Essentially, if this error happens, I intentionally want the program not to be able to run.
Should I make this a checked exception, or an unchecked exception, keeping in mind that the program should not run if the Date restriction isn't met?