- public int test()
- {
- int a = 1;
- try
- {
- return a;
- }catch
- {
- //todo:handle exception
- }finally
- {
- a++;
- }
- return a;
- }
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
上面的輸出結果很好分析,首先執行try中的println,然後執行return,在return前,去執行finally中的println,執行完finally中的代碼後再去try中return,然後輸出main函數中的結果。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的返回值問題了。