null value for a date throwing a NullPointerException

 if (aDate.after(cottageHospital.getLastWardChangeDate(thePatient)))
  {
     Ward newWard = (Ward) changeWardNewWardList.getSelectedValue();
     changeWardArea.setText("Patient " + thePatient + " moved to " + 
                            newWard + "ward.");
     cottageHospital.changeWard(thePatient, newWard, aDate);

  }

I have an if statement that is part of a larger method, the statement compares a date, aDate, with another date value. Problem is that the first time this method is used the date that aDate is trying to compare to is null, throwing a NullPointerExCeption.

What would be the best way to go about handling this exception?


您可以添加空检查:

theDate = cottageHospital.getLastWardChangeDate(thePatient);
if (theDate != null && aDate.after(theDate))

You should not handle the exception but make sure it does not appear at all -> make sure aDate never is null. If this is not possible, add a null check before the comparison.

Null check would look like this:

if (aDate != null && aDate.after(cottageHospital.getLastWardChangeDate(thePatient))) {
    Ward newWard = (Ward) changeWardNewWardList.getSelectedValue();
    changeWardArea.setText("Patient " + thePatient + " moved to " + newWard + "ward.");
    cottageHospital.changeWard(thePatient, newWard, aDate);
}

Cleaner way would be to make sure aDate never is null though.

链接地址: http://www.djcxy.com/p/13270.html

上一篇: 使用throw命令不会引发异常

下一篇: null值为引发NullPointerException的日期