public
class Ex1 {
public static void main(String[] args) {
System.out.println(Ex1.getResult());
}
public static int getResult(){
int a =100;
try{
return a+10; // 注意,java的基礎數據類型是值傳遞,這里的返回值已經和上面的a沒有關系了
} catch(Exception e){
public static void main(String[] args) {
System.out.println(Ex1.getResult());
}
public static int getResult(){
int a =100;
try{
return a+10; // 注意,java的基礎數據類型是值傳遞,這里的返回值已經和上面的a沒有關系了
} catch(Exception e){
e.printStackTrace();
} finally{
return a; // 最后再把值重定向到a(相當於將try中的返回值覆蓋掉),所以輸出還是100
}
}
}
} finally{
return a; // 最后再把值重定向到a(相當於將try中的返回值覆蓋掉),所以輸出還是100
}
}
}
再看一個例子:
public
class Ex1 {
public static void main(String[] args) {
try{
System.out.println(Ex1.getResult());
} catch(Exception e){
e.printStackTrace();
System.out.println("截獲異常catch");
} finally{
System.out.println("異常處理finally");
}
}
public static int getResult() throws Exception{
int a =100;
try{
a=a+10;
throw new RuntimeException();
} catch(Exception e){
System.out.println("截獲異常並重新拋出異常");
throw new Exception();
} finally{
return a;
}
}
}
public static void main(String[] args) {
try{
System.out.println(Ex1.getResult());
} catch(Exception e){
e.printStackTrace();
System.out.println("截獲異常catch");
} finally{
System.out.println("異常處理finally");
}
}
public static int getResult() throws Exception{
int a =100;
try{
a=a+10;
throw new RuntimeException();
} catch(Exception e){
System.out.println("截獲異常並重新拋出異常");
throw new Exception();
} finally{
return a;
}
}
}
輸出如下:
截獲異常並重新拋出異常
110
異常處理finally
關鍵的“截獲異常catch”卻沒有執行!!!
原因是在getResult()的finally中return一個值,等同於告訴編譯器該方法沒有異常,但實際上異常是有的,這樣的結果是該方法的調用者卻捕獲不到異常,相對於異常被無端的被吃掉了,隱藏殺機啊!!
結論:不要再finally中試圖return一個值,這樣可能會導致一些意想不到的邏輯錯誤,finally就是用來釋放資源的!!