try/catch/finally语句下,finally子句是肯定会执行的。但是很多人做不同的测试,却得出了不同的结论。
具体的原理最好是去看《深入java虚拟机》,里面对jsr、ret等几个指令做了详细的说明。这里不深入分析,而仅仅是从表现形式上看一下finally的特征。
代码:
/* * author: Zang XT */ public class TestFinal { public static void main(String[] args) { System.out.println("test1:" + testFinal1()); System.out.println("test2:" + testFinal2()); System.out.println("test3:" + testFinal3()); System.out.println("test4:" + testFinal4()); } static int testFinal1() { int i = 1; try { return i; } finally { System.out.println("in testFinal1():finally 肯定会被执行的!"); i = 48; } } static String testFinal2() { String str = "try"; try { return str; } finally { System.out.println("in testFinal2():finally 肯定会被执行的!"); str = "finally"; } } static StringBuilder testFinal3() { StringBuilder build = new StringBuilder("try "); try { return build; } finally { System.out.println("in testFinal3():finally 肯定会被执行的!"); build.append("finally"); build = new StringBuilder("你猜我是谁!"); } } static String testFinal4() { try { return "return in try"; } finally { System.out.println("in testFinal4():finally 肯定会被执行的!"); return "return in finally"; } } }
输出是:
in testFinal1():finally 肯定会被执行的!
test1:1
in testFinal2():finally 肯定会被执行的!
test2:try
in testFinal3():finally 肯定会被执行的!
test3:try finally
in testFinal4():finally 肯定会被执行的!
test4:return in finally