1.首先尝试在try中return,看finally是否能执行到,测试代码如下:
public class FinallyTest {
结果是:
public String returnString() {
String str;
try {
str = "Hello, William";
System.out.println("This is try block.");
return str;
}
catch(Exception e) {
System.out.println("This is catch block.");
}
finally {
System.out.println("This is finally block.");
}
return null;
}
}
This is try block.
This is finally block.
可见不管try里是否有return,finally最终仍会执行到。
2.但是在try中System.exit(0),finally还会不会执行呢?还是来段测试代码,如下:
public class FinallyTest1 {
结果是:
public static String returnString() {
String str;
try {
str = "This is try block.";
System.out.println(str);
System.exit(0);
}
catch(Exception e) {
System.out.println("This is catch block.");
}
finally {
System.out.println("This is finally block.");
}
return null;
}
}
This is try block.
可见,这种情况下,finally还未被执行,程序就退出了。碰到这种情况,如果还想在程序退出之前执行一些代码,可以参见addShutdownHook这个函数。
总结:return之前没有System.exit() ;之类的直接让应用停下来的代码的话, finally中的代码就会执行 并且是在return之前执行
本文通过两个示例探讨了Java中finally块的执行机制。首先分析了在try块内使用return的情况下finally块是否能够得到执行;其次研究了当try块内调用System.exit(0)时finally块的执行情况。
1628

被折叠的 条评论
为什么被折叠?



