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:
if(date == null) return false;
But even that's not graceful. You may want to do something with this.date
or throw an exception up if that's the desired behavior.
What you are really seeking is either:
ParseException
- thrown by a DateFormat
object when it attempts to parse()
, which would happen before your set methodIllegalArgumentException
- thrown by a SimpleDateFormat
constructor, 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 Date
object, it is either null
or valid.