Java IllegalArgumentException在';如果';条件
我想将lastModifiedDate更新为当前日期并执行一些操作,前提是当前日期大于lastModifiedDate 但是当第一次执行时,我担心在if条件中的“Java IllegalArgumentException在';如果';条件,java,if-statement,exception,illegalargumentexception,Java,If Statement,Exception,Illegalargumentexception,我想将lastModifiedDate更新为当前日期并执行一些操作,前提是当前日期大于lastModifiedDate 但是当第一次执行时,我担心在if条件中的“dateToday.isAfter(lastModifiedDate.get(“lastUpdated”))”附近获取NullPointerException,因为HashMap中还没有“lastUpdated”键的键值对。下面是代码 import java.util.HashMap; import org.joda.time.Date
dateToday.isAfter(lastModifiedDate.get(“lastUpdated”))
”附近获取NullPointerException,因为HashMap中还没有“lastUpdated”键的键值对。下面是代码
import java.util.HashMap;
import org.joda.time.DateTimeZone;
import org.joda.time.LocalDate;
public class TestDate {
static HashMap<String, LocalDate> lastModifiedDate = new HashMap<>();
static int unityResponsesCount;
public void resetUnityResponsesCount() {
unityResponsesCount = 0;
}
/**
* @param args
*/
public static void main(String[] args) {
LocalDate dateToday = LocalDate.now(DateTimeZone.getDefault());
if (lastModifiedDate.isEmpty() || dateToday.isAfter(lastModifiedDate.get("lastUpdated"))) {
lastModifiedDate.put("lastUpdated", dateToday);
TestDate testDate = new TestDate();
testDate.resetUnityResponsesCount();
}
}
}
import java.util.HashMap;
导入org.joda.time.DateTimeZone;
导入org.joda.time.LocalDate;
公共类TestDate{
静态HashMap lastModifiedDate=新HashMap();
静态int unityResponsesCount;
public void resetUnityResponseCount(){
UnityResponseCount=0;
}
/**
*@param args
*/
公共静态void main(字符串[]args){
LocalDate dateToday=LocalDate.now(DateTimeZone.getDefault());
if(lastModifiedDate.isEmpty()| | dateToday.isAfter(lastModifiedDate.get(“lastUpdate”)){
lastModifiedDate.put(“LastUpdate”,dateToday);
TestDate TestDate=新的TestDate();
testDate.resetUnityResponseCount();
}
}
}
在运行之前,我调试了代码,当我只检查“dateToday.isAfter(lastModifiedDate.get(“lastUpdate”)
”时,我得到
java.lang.IllegalArgumentException:Partial在处不能为null
org.joda.time.base.AbstractPartial.isAfter(AbstractPartial.java:351)
位于org.thermory.scan.qa.util.TestDate.main(TestDate.java:25)
但是,如果我检查完整的if语句,lastModifiedDate.isEmpty()| | dateToday.isAfter(lastModifiedDate.get(“lastUpdate”)
,我得到的是“TRUE”。
如果这个If语句产生了异常,我应该提供单独的If条件,每个条件中都有相同的赋值,lastModifiedDate.put(“lastUpdated”,dateToday)代码>
我只是很惊讶,IllegalArgumentException是如何在if条件中自动处理的。这个条件
(lastModifiedDate.isEmpty() || dateToday.isAfter(lastModifiedDate.get("lastUpdated")))
正在使用短路或操作员|
这意味着首先计算lastModifiedDate.isEmpty()
,如果为true,则不计算dateToday.isAfter(lastModifiedDate.get(“lastUpdate”)
,因此不会引发异常。整个表达式被视为true。如果lastModifiedDate.isEmpty()
为true,则dateToday.isAfter(lastModifiedDate.get(“lastUpdate”)
不会被计算。Hello@khelwood,是吗?