要得出return a 为多少,是不是有点让人迷糊。
- public int test()
- {
- int a = 1;
- try
- {
- return a;
- }catch
- {
- //todo:handle exception
- }finally
- {
- a++;
- }
- return a;
- }
上面的输出结果很好分析,首先执行try中的println,然后执行return,在return前,去执行finally中的println,执行完finally中的代码后再去try中return,然后输出main函数中的结果。public class JVMTest {
public static void main(String[] args){
System.out.println("aa:" + aa());
}
public static int aa(){
int a = 1;
int b = 10;
try{
System.out.println("abc");
return a;
}finally{
a = 2;
System.out.println("a: "+ a);
}
}
}
abc
a: 2
aa: 1
那么,此时的输出结果是什么呢?public class FinallyTest { public static void main(String[] args) { System.out.println("getValue()返回值为:" + getValue()); } public static int getValue() { try { return 0; } finally { return 1; } } }
a finally clause is always entered with a reason. That reason may be that the trycode finished normally, that it executed a control flow statement such as return, or that an exception was thrown in code executed in the TRy block. The reason is remembered when the finally clause exits by falling out the bottom. However, ifthe finally block creates its own reason to leave by executing a control flow statement (such as break or return) or by throwing an exception, that reason supersedes the original one, and the original reason is forgotten. For example, consider the following code:
try {
// ... do something ...
return 1;
} finally {
return 2;
}
When the TRy block executes its return, the finally block is entered with the "reason" of returning the value 1. However, inside the finally block the value 2 is returned, so the initial intention is forgotten. In fact, if any of the other code in the try block had thrown an exception, the result would still be to return 2. If the finally block did not return a value but simply fell out the bottom, the "return the value 1" reason would be remembered and carried out.
上述红色关键字体的意思是,当try正常结束(code finished normally)包括return, or that an exception,程序就会跳转到finally块中去,如果finally中没有such as break or return or by throwing an exception这些发生,try中的return就会正常返回;如果finally中有break 或者 return 或者抛出异常,那么try中的return值就会被清除,按照finally中的结果来返回。
按照上面的描述,是不是对finally的用法更加了解了呢。
为什么会出现这种分情况的讨论,究其原因,都是java的设计规则引起的。结合上面的三段代码及运行过程分析,可以分析任何try 和finally的返回值问题了。