Finally and Return in Java


元の住所:http://blog.163.com/wingstart@126/blog/static/1059200620 101021135455/いくつかの問題から始めます。1、finallyは必ず実行しますか?2、次のステートメントの実行結果は:
public class FinallyTest {

         public static void main(String[] args) {
            System.out.println("getValue()    :" + getValue());
         }
  
         public static int getValue() {
            try {
                return 0;
            } finally {
                return 1;
            }
         }
}
3、次のステートメントの実行結果は:
public class FinallyTest {

         public static void main(String[] args) {
             System.out.println("getValue()    :" + getValue());
         }
        
         public static int getValue() {
             int i = 1;
             try {
                 return i;
             } finally {
                 i++;
             }
         }
}
答え:
1.答えは否定的です。
  tryではSystem.exit(0)を実行しました。操作はfinallyでは実行されません。また、フリーズ、電源オフはfinallyが実行されません。
2.出力1
3.出力1
解釈は「THE Java Prograamming Language、Fourth Edition」に由来します。
A finally clause is always entered with a reason. 
That reason may be that the try code 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, if the 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 thefinally block did not return a value but simply fell out the bottom, 
the "return the value 1" reason would be remembered and carried out.
まとめ:
finallyにreturn文がある時、tryの中のreturnは捨てられます。finallyにreturn文がない場合、tryでreturnの値は保存されて返されます。