• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
乐碎碎
程序媛想的事儿
博客园    首页    新随笔    联系   管理    订阅  订阅
finally块中的代码一定会执行吗?

在Sun Tutorial中有这样一句话:The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs.  看来finally块中的语句应该是总会执行的。

  先来写一个最常见的写法:

 

 1 public class finally_test {
 2     
 3     public static void main(String[] args){
 4         try{
 5             System.out.println("11");
 6             //System.out.println(args[0]);
 7             System.out.println("nomal");
 8         }catch(Exception e){
 9             System.out.println("exception");
10         }finally{
11             System.out.println("finally");
12         }        
13     }
14 }

 

执行结果:

11
nomal
finally

System.out.println("11");换成 System.out.println(args[0]);
无输入的情况下:
执行结果:

exception
finally

运行这段代码,很明显,不论是否有参考输入,"I'm finally."这句话都会打印出来。这是最常用的写法,很显然与Tutorial中的说明是相符的。

  下面我们再进一步想一下,假如在try或是catch块中使用了return语句,那么会怎么样呢?

  我们将代码稍做修改:

 1 public class finally_test {
 2     
 3     public static void main(String[] args){
 4         try{
 5             System.out.println("11");
 6             System.out.println(args[0]);
 7             System.out.println("nomal");
 8              return;  
 9         }catch(Exception e){
10             System.out.println("exception");
11              return;  
12         }finally{
13             System.out.println("finally");
14         }        
15     }
16 }

执行结果:

11
exception
finally

很明显,finally中的代码还是执行了。再次修改代码,将return语句修改成System.exit(),看一下执行结果。

 

 1 public class finally_test {
 2     
 3     public static void main(String[] args){
 4         try{
 5             System.out.println("11");
 6             System.out.println("nomal");
 7             System.exit(0); 
 8         }catch(Exception e){
 9             System.out.println("exception");
10             System.exit(0); 
11         }finally{
12             System.out.println("finally");
13         }        
14     }
15 }

执行结果:

11
nomal

 运行代码,终于,"I'm finally."不见了。

  为什么System.exit()有这么强大的力量呢,让我们看一下API中的说明:exit(int status): Terminates the currently running Java Virtual Machine。原来是这样,JVM都被终止掉了,当然不会再执行finally中的语句了。

  下面是我们的结论:

  在不终止VM的情况下,finally中的代码一定会执行。

 


 参考:

1.Java牛角尖【013】: finally块中的代码一定会执行吗?

2.

posted on 2014-03-30 20:33  xingle0917  阅读(895)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3