Java学习之finally

如果catch中有return语句,finally里面的语句还会执行吗?

  会执行,在return语句的中间执行

 1 public class Test{
 2         public static void main(String[] args){
 3              System.out.println(getInt());
 4         }
 5         public static int getInt(){
 6         int a = 10;
 7         try{
 8              System.out.println(1/0);
 9         }catch(Exception e){
10             e.printStackTrace();
11             a=10;
12             return a;
13         }finally{
14             a = 100;
15         }
16      }
17 }
18     

出现异常后,程序执行到第12句,a=10,接着执行return语句,由于有finally语句,所以跳转到finnally语句中,此时a=100,然后程序又跳转到Catch中的return语句,此时a又恢复10,所以finally中的语句会执行,在return的中间执行。

如果将程序修改为:

 

 1 public class Example2 {
 2     public static void main(String[] args) throws HanderException {
 3         System.out.println(getInt());
 4     }
 5     
 6     public static int getInt(){
 7         int a = 10;
 8         try{
 9              System.out.println(1/0);
10         }catch(Exception e){
11             e.printStackTrace();
12             a=10;
13             return a;
14         }finally{
15             a = 100;
16             return a;
17         }
19     }
20 }

 

则执行结果a的值为100,执行完finally中的语句就直接返回了

 

posted @ 2015-09-06 21:48  天~宇~翱~翔  阅读(235)  评论(0编辑  收藏  举报