现在的位置: 首页 > 综合 > 正文

解析Java finally

2013年04月21日 ⁄ 综合 ⁄ 共 1190字 ⁄ 字号 评论关闭

问题分析 


首先来问大家一个问题:finally 语句块一定会执行吗? 

很多人都认为 finally 语句块是肯定要执行的,其中也包括一些很有经验的 Java 程序员。可惜并不像大多人所认为的那样,对于这个问题,答案当然是否定的,我们先来看下面这个例子。
清单 1.

  1. public class Test { 
  2. public static void main(String[] args) { 
  3. System.out 
  4. .println("return value of test(): " + test 
  5. ()); 
  6.  
  7. public static int test() { 
  8. int i = 1
  9. // if(i == 1) 
  10. // return 0; 
  11. System.out 
  12. .println("the previous statement of try block"); 
  13. i = i / 0
  14. try { 
  15.     System.out 
  16. .println("try block"); 
  17.       return i; 
  18.      }finally { 
  19.      System.out 
  20. .println("finally block"); 
  21. }  

清单 1 的执行结果如下:

the previous statement of try block
Exception in thread "main" java.lang.ArithmeticException: / by zero
at com.bj.charlie.Test.test(Test.java:15)
at com.bj.charlie.Test.main(Test.java:6) 

另外,如果去掉上例中被注释的两条语句前的注释符,执行结果则是:

  1. return value of test(): 0  

在以上两种情况下,finally 语句块都没有执行,说明什么问题呢?只有与 finally 相对应的 try 语句块得到执行的情况下,finally 语句块才会执行。以上两种情况,都是在 try 语句块之前返回(return)或者抛出异常,所以 try 对应的 finally 语句块没有执行。 


那好,即使与 finally 相对应的 try 语句块得到执行的情况下,finally 语句块一定会执行吗?不好意思,这次可能又让大家失望了,答案仍然是否定的。请看下面这个例子(清单 2)。

清单 2.

  1. public class Test { 
  2. public static void main(String[] args) { 
  3. System.out 
  4. .println("return value of test(): " + test 
  5. ()); 
  6.  
  7. public static int test() { 
  8. int i = 1
  9. try { 
  10. System.out 
  11. .println("try block"); 
  12. System.exit 

抱歉!评论已关闭.