Is the Java finally statement executed before or after the return?

Source: Internet
Author: User

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?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.