Java语言里,在try语句块中return,还会继续执行finally语句块中的语句么?

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这个函数。具体这个函数的用法,将在另外的博客中详解。

你可能感兴趣的:(exit,finally,try,休闲,addShutdownHook)