以下兩種情況要避免在finally中使用return
1. 如果catch塊中捕獲了異常,並將該異常throw給上級調用者處理,但finally中return了,那么catch塊中的throw就失效了,上級方法調用者是捕獲不到異常的
例: 如下代碼上級調用者是捕獲不到異常的
public static void main(String[] args){ try { System.out.println(work()); }catch (Exception e){ //捕獲不到異常 e.printStackTrace(); } } public static int work(){ int c = 0; try{ c = 3/0; }catch (Exception e){ //除以0 ,會有異常:ArithmeticException: / by zero throw e; } finally { return c; } }
2 . 在finally里的return之前執行了其他return ,最終的返回值還是finally中的return
例 : 如下代碼返回的是finally里return的5
public static void main(String[] args){ System.out.println(work()); } public static int work(){ int x =3; try{ return x; }catch (Exception e){ e.printStackTrace(); } finally { x = 5; return x; } }