以下两种情况要避免在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; } }