码迷,mamicode.com
首页 > 编程语言 > 详细

Java学习之finally

时间:2015-09-06 22:52:22      阅读:315      评论:0      收藏:0      [点我收藏+]

标签:

如果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中的语句就直接返回了

 

Java学习之finally

标签:

原文地址:http://www.cnblogs.com/sunfie/p/4787477.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!