異常處理
當for循環遇上try-catch
首先是不建議在循環體內部進行try-catch操作,效率會非常低,這里僅僅是測試這種情況,具體的業務場景建議還是不要在循環里try-catch
@Test
public void forThrow(){
final int size = 6;
for (int i=0; i<size; i++){
if(i > 3){
throw new IllegalArgumentException(i+" is greater than 3");
}
System.out.println(i);
}
}
上面執行了一個for循環,當i大於5就拋出異常,這里由於沒有捕獲異常,程序直接終止。 下面來看看捕獲異常后的結果
@Test
public void forThrowException(){
final int size = 6;
for (int i=0; i<size; i++){
try {
if(i > 3){
throw new IllegalArgumentException(i+" is greater than 3");
}
}catch (IllegalArgumentException e){
e.printStackTrace();
}
System.out.println(i);
}
}
由於內部捕獲了異常,程序打印出堆棧,程序沒有終止,直到正常運行結束。
進行數據運算時,如果拋出了異常,數據的值會不會被改變呢?
@Test
public void forExceptionEditValue(){
final int size = 6;
int temp = 12345;
for (int i=0; i<size; i++){
try {
temp = i / 0;
}catch (ArithmeticException e){
e.printStackTrace();
}
System.out.println("i = "+i+", temp = "+temp);
}
}
可以看到,當想要改變temp的值的時候,由於數據運算拋出了異常,temp的值並沒有改變!