@Test
public void loopTryCatchTest() throws Exception {
Map<String, Object> a = new HashMap();
a.put("a", "1");
a.put("b", null);
a.put("c", "3");
for (Map.Entry<String, Object> moEntry : a.entrySet()) {
try{
boolean flag = moEntry.getValue().equals("1");
System.out.println(moEntry.getKey() + "," + moEntry.getValue() + "," + flag);
} catch(Exception e){
System.out.println("異常跳出" + e);
//continue;--- 不需要寫continue,因為寫不寫,都會繼續循環,不會異常后直接退出的。
}
}
}
執行結果:
a,1,true
異常跳出java.lang.NullPointerException
c,3,false
如果try包在for循環外面,則無法達到預期效果,遇到異常拋出,被catch住后,循環無法繼續執行。
@Test
public void loopTryCatchTest() throws Exception {
Map<String, Object> a = new HashMap();
a.put("a", "1");
a.put("b", null);
a.put("c", "3");
try {
for (Map.Entry<String, Object> moEntry : a.entrySet()) {
boolean flag = moEntry.getValue().equals("1");
System.out.println(moEntry.getKey() + "," + moEntry.getValue() + "," + flag);
}
}catch (Exception e) {
System.out.println("異常跳出" + e);
}
}