上一段代碼
public static int testTry(){
int i = 1;
try {
i++;
System.err.println("我是try中return前的正常方法...."+i);
return i;
}catch (Exception e){
i++;
System.err.println("我是catch中的方法執行...."+i);
}finally {
i++;
System.err.println("我是finally中的正常方法....."+i);
}
System.err.println("我是try catch外的方法,我執行了嗎?");
return i;
}
public static int testCatch(){
int i = 1;
try {
int i1 = i / 0;
System.err.println("我是try中return前的正常方法...."+i);
}catch (Exception e){
i++;
System.err.println("我是catch中的方法執行...."+i);
return i;
}finally {
i++;
System.err.println("我是finally中的正常方法....."+i);
}
System.err.println("我是try catch外的方法,我執行了嗎?");
return i;
}
public static void main(String[] args) {
int i = testTry();
System.err.println("testTry方法執行結束...."+i);
System.err.println("=========================================");
int i1 = testCatch();
System.err.println("testCatch方法執行結束..."+i1);
}
總結:
基本數據類型
finally最終都會執行;
return 之前的數據不會變化,即使後面finally對數據進行了增加;
public static List testTry(){
List result = new ArrayList();
try {
result.add("1");
System.err.println("我是try中return前的正常方法...."+result.size());
return result;
}catch (Exception e){
result.add("2");
System.err.println("我是catch中的方法執行...."+result.size());
}finally {
result.add("3");
System.err.println("我是finally中的正常方法....."+result.size());
}
System.err.println("我是try catch外的方法,我執行了嗎?");
return result;
}
public static List testCatch(){
List result = new ArrayList();
try {
Object o = result.get(100);
System.err.println("我是try中return前的正常方法...."+result.size());
}catch (Exception e){
result.add("5");
System.err.println("我是catch中的方法執行...."+result.size());
return result;
}finally {
result.add("6");
System.err.println("我是finally中的正常方法....."+result.size());
}
System.err.println("我是try catch外的方法,我執行了嗎?");
return result;
}
public static void main(String[] args) {
int i = testTry().size();
System.err.println("testTry方法執行結束...."+i);
System.err.println("=========================================");
int i1 = testCatch().size();
System.err.println("testCatch方法執行結束..."+i1);
}
此時驗證的結果就會發現,當時引用數據類型的時候,這個值就變化了....
一個是基本數據類型,一個是引用數據類型,這樣就很容易理解了....
引用數據類型拿到是List的地址庫引用,後期對該引用對應的值進行了更改,所以再去size的時候,是有變化的,也是可以解釋得通的..並不悖於上面的結論;
return先將結果保留,等執行完finally後再返回給調用者;