Is there some sort of exception in Java to catch an invalid Date object? I’m trying to use it in the following method, but I don’t know what type of exception to look for. Is it a ParseException.
public boolean setDate(Date date) {
this.date = date;
return true;
}
In the method you provide, there is no way to catch an exception, because none will be thrown by the simple assignment. All you can do is maybe the below change:
But even that’s not graceful. You may want to do something with
this.dateor throw an exception up if that’s the desired behavior.What you are really seeking is either:
ParseException– thrown by aDateFormatobject when it attempts toparse(), which would happen before your set methodIllegalArgumentException– thrown by aSimpleDateFormatconstructor, again it would happen before your set method. Indicates you provided an invalid format string.You’d want to catch one of those (probably #1). But it has to happen before your method call. Once you have a
Dateobject, it is eithernullor valid.