注:文章参考自:https://www.ibm.com/developerworks/cn/java/j-lo-finally/
引用内容为java官方文档:《The Java™ Tutorials》
经典的try...catch...finally语句大家一定不陌生。尤其是这个finally语句块,一般都用来处理出现异常后的善后工作,例如:关闭IO,数据库连接,保存信息等等。但你有没有想过这几个问题:
1.finally语句块的执行时间和顺序。它是在哪一步执行的?
2.finally语句块真的一定会执行吗?存不存在不执行的情况
例如下面这块代码,你认为最终结果会是多少;
public static void main(String[] args){
System.out.println(testFinally());
}
public static int testFinally(){
int i = 0;
try {
return 1;
}finally {
return 3;
}
}
答案是:3;
有些人肯定想到:finally的语句可能是在return语句之后执行的。再来看看下面这个例子:
public static int testFinally(){
int i = 0;
return;
try {
return 1;
}finally {
i = 3;
}
}
我们让函数在进入try块之前终止,然而上面这段语句根本无法通过编译
那我们再换个方法
public static int testFinally(){
int i = 0;
i = 0/0;
try {
return 1;
}finally {
sout("This is finally语句块");
}
}
让它抛个异常来试试,结果
finally语块仍然没有执行,看来finally语句块并不是一定执行的。
finally块的运行机制到底是怎样的呢?java官网上是这么说的:
The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally by passed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.
Note: If the JVM exits while the try or catch code is being executed, then the finally block may not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.
If a finally clause is present with a try, its code is executed after all other processing in the try is complete. This happens no matter how completion was achieved, whether normally, through an exception, or through a control flow statement such as return or break.
什么意思呢?简单来说就是:
1.如果程序进入try语句块,那么try语句块运行结束之后(包括通过异常和控制流语句:continue、return、break等结束)对应的finally语句块一定会执行。
2.遇到下列情况finally不被执行:
程序异常终止(如System.exit(0)),线程结束或被暂停,没有进入相应的try块
所以,finally拥有更改返回值的能力,如果返回的是引用类型,finally里修改对象属性时,输出的内容也会改变。这点应该很好理解。