try放在for循環里面和外面的區別是什么呢?先看看下面的代碼的區別:
public class Test {
public void test1(){
for (int count = 0; count < 6; count++) {
try {
int x;
if (count == 3)
x = 1 / 0;
else{
x = count;
System.out.println(x);
}
} catch(Exception e){
System.out.println("異常");
}
}
}
public void test2(){
try {
for (int count = 0; count < 6; count++) {
int x;
if (count == 3)
x = 1 / 0;
else{
x = count;
System.out.println(x);
}
}
} catch (Exception e) {
System.out.println("異常");
}
}
public static void main(String[] args) throws Exception {
Test te = new Test();
te.test1();
System.out.println("------------------------");
te.test2();
}
}
結果:
0
1
2
異常
4
5
------------------------
0
1
2
異常
總結:try放在for循環的里面所有的for循環都會執行,當遇到異常時,拋出異常繼續執行;放在外面,當遇到異常時,拋出異常,后面的循環就會終止,並不會執行。
對於放到里面還是外面,有時候還看自己的選擇,一般建議放到里面比較好。