Question

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;
    }
Was it helpful?

Solution

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:

  1. ParseException - thrown by a DateFormat object when it attempts to parse(), which would happen before your set method
  2. IllegalArgumentException - 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.

OTHER TIPS

This might not be related to the original question. But you must notice the method name, which is setDate(). Do you think it sounds like it will return something? Or if it may, then do you think its a good idea to return a boolean there? IMO, do something like this,

public void setDate(Date date) {
    this.date = date;                
}

public boolean isDateNull() { // or something
    return this.date == null;                
}

In this method, there is no need to worry about an exception. The date is already created by the time you get into this method. If you are parsing a date, it would have done outside of this code. The best you could do is make sure the date is not null.

It depends on what you mean by an invalid date. Did you mean to give us a method signature that looked more like this?

public void setDate(String date) throws ParseException {
   this.date = SomeDateFormat.getInstance().format(date);
}

Otherwise, as the others stated the simple act of assigning a Java date object to a field shouldn't be exceptional as it is either an instance of Date already, or null.

If you are just trying to parse a string into a java.util.Date, look at DateFormat, FastDateFormat (apache, thread safe), or Joda Time.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top