Finally in Java

2678 ワード

いくつかの問題から始めます.
一、finallyは必ず実行しますか?
二、次の文の実行結果は次のとおりです.
public class FinallyTest {
         public static void main(String[] args) {
                   System.out.println("getValue()    :" + getValue());
         }
        
         public static int getValue() {
                   try {
                            return 0;
                   } finally {
                            return 1;
                   }
         }
}

三、次の文の実行結果は次のとおりです.
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++;
                   }
         }
}

まず、最初の質問は、答えは否定的です.tryでSystem.exit(0)を実行しました.操作finallyは実行されず、またハングアップ、電源オフによりfinallyは実行されません.
次の2つの質問について、まず『THE Java』から抜粋してみましょう.™ Programming Language,Fourth Edition,By Ken Arnold,James Gosling,David Holmesのいくつかの言葉:
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 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.
赤と青のフォントの寸法の解釈から分かるように、finallyにreturn文がある場合、tryのreturnは捨てられます.finallyにreturn文がない場合、tryのreturnの値は保存され、返されます.
したがって、2番目の質問の答えは、getValue()の戻り値は:1です.
3番目の質問の答えは、getValue()の戻り値が:1です.