问题分析
首先来问大家一个问题:finally 语句块一定会执行吗?
很多人都认为 finally 语句块是肯定要执行的,其中也包括一些很有经验的 Java 程序员。可惜并不像大多人所认为的那样,对于这个问题,答案当然是否定的,我们先来看下面这个例子。
清单 1.
- public class Test {
- public static void main(String[] args) {
- System.out
- .println("return value of test(): " + test
- ());
- }
- public static int test() {
- int i = 1;
- // if(i == 1)
- // return 0;
- System.out
- .println("the previous statement of try block");
- i = i / 0;
- try {
- System.out
- .println("try block");
- return i;
- }finally {
- System.out
- .println("finally block");
- }
- }
- }
清单 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)
另外,如果去掉上例中被注释的两条语句前的注释符,执行结果则是:
- return value of test(): 0
在以上两种情况下,finally 语句块都没有执行,说明什么问题呢?只有与 finally 相对应的 try 语句块得到执行的情况下,finally 语句块才会执行。以上两种情况,都是在 try 语句块之前返回(return)或者抛出异常,所以 try 对应的 finally 语句块没有执行。
那好,即使与 finally 相对应的 try 语句块得到执行的情况下,finally 语句块一定会执行吗?不好意思,这次可能又让大家失望了,答案仍然是否定的。请看下面这个例子(清单 2)。
清单 2.
- public class Test {
- public static void main(String[] args) {
- System.out
- .println("return value of test(): " + test
- ());
- }
- public static int test() {
- int i = 1;
- try {
- System.out
- .println("try block");
- System.exit