There are at least two cases in which the finally statement is not executed:
(1) The Try statement is not executed, as returned before the try statement, so that the finally statement does not execute, which also shows that the finally statement is executed by the necessary rather than sufficient condition is: the corresponding Try statement must be executed to.
(2) There is system.exit (0) in the try block, such a statement, System.exit (0), terminates the Java Virtual Machine JVM, even the JVM is stopped, all is finished, and the finally statement is not executed.
The rest is like this.
The finally statement is executed after the return statement of the try is executed and the return is returned.
public class FinallyTest1 {public static void Main (string[] args) { System.out.println (test1 ()); } public static int test1 () { int b = +; try { System.out.println ("try block"); Return B + + +; } catch (Exception e) { System.out.println ("Catch block"); } finally { System.out.println ("finally Block"); if (b >) { System.out.println ("b>25, B =" + B); } } return b; } }
Operation Result:
Try blockfinally blockb>25, B = 100100
Indicates that the return statement has executed and then executes the finally statement, but does not return directly, but waits until the finally statement is finished and returns the result.
public class FinallyTest1 {public static void Main (string[] args) { System.out.println (test11 ()); } public static String test11 () { try { System.out.println ("try block"); return test12 (); } finally { System.out.println ("finally Block"); } } public static String test12 () { System.out.println ("return statement"); Return "after Return"; } }
Run results
Try Blockreturn statementfinally Blockafter return
Is the Java finally statement executed before or after the return?