finally块中的代码什么时候被执行
1.finally块的作用
在Java语言的异常处理中,finally块的作用就是为了保证无论出现什么情况,finally块里的代码块一定会被执行。由于程序执行return就意味着结束对当前函数的调用并跳出这个函数体,所以任何语句要执行都只能在return前执行(除非碰到exit函数)。
例一
public class Test{
public static int testFibally(){
try{
return 1;
}catch(Exception e){
return 0;
}finally{
System.out.println("execute finally");
}
}
public static void main(String[] args){
int result = testFinally();
System.out.println(result);
}
}
运行结果:
execute finally
1
从上面的例子可以看出在执行retrun
语句前确实执行了finally块中的代码。
例二
public class Test{
public static int testFibally(){
try{
return 1;
}catch(Exception e){
return 0;
}finally{
System.out.println("execute finally");
return 3;
}
}
public static void main(String[] args){
int result = testFinally();
System.out.println(result);
}
}
运行结果:
execute finally
3
当finally块中有return
语句时,将会覆盖函数中其他return
语句。
例三
import java.sql.SQLOutput;
public class Test {
public static int testFinally(){
int result = 1;
try{
result = 2;
return result;
}catch(Exception e){
return 0;
}finally{
result = 3;
System.out.println("execute finally1");
}
}
public static StringBuffer testFinally2(){
StringBuffer s = new StringBuffer("Hello");
try{
return s;
}catch (Exception e){
return null;
}finally {
s.append(" World");
System.out.println("execute finally2");
}
}
public static void main(String[] args){
int resultVal = testFinally();
System.out.println(resultVal);
StringBuffer resultRef = testFinally2();
System.out.println(resultRef);
}
}
运行结果:
execute finally1
2
execute finally2
Hello World
程序在执行到return
语句时首先将返回值存储在一个指定的位置,其次去执行finally块,最后再返回。此时修改result
的值将不会影响到程序的返回结果。(finally块里的内容仍然会被执行,如Hello World
的输出,此时的s
为引用类型)。
新手上传
如有错误,欢迎指出ヾ(≧▽≦*)o
from《java程序员面试笔试宝典》