Execution of finally blocks in Java

Source: Internet
Author: User

In the try{}catch{}finally{} block, you know that the finally child block is sure to execute. There are, of course, individual cases where the finally child block is not executed when a forced exit System.exti (int) appears in the try{} or catch{} block. This situation is not within the scope of today's discussion.
Look at the code more intuitively:

Java code
  1. Package practice;
  2. Public class Finallyrun {
  3. private int a = 0;
  4. public int getInt () {
  5. try {
  6. A = 1;
  7. return A;
  8. } finally {
  9. A = 2;
  10. return A;
  11. }
  12. }
  13. public static void Main (string[] args) {
  14. Finallyrun f = new Finallyrun ();
  15. int tmp = F.getint ();
  16. System.out.println ("f.getint () =" + tmp);
  17. System.out.println ("F.A =" + F.A);
  18. }
  19. }


I a=1 out a break, one-step trace found: Although the try contains a return, and the return statement in the try executes, the program jumps to finally, continues to run, and then returns the Exit Getint () method. The results are as follows:

Java code
    1. F.getint () = 1
    2. F.A = 2


As you can see from the results, the GETINT () method returns 1 of the value, while the value of variable A is 2. Cancel the comment in the code and run the program with the following results:

Java code
    1. F.getint () = 2
    2. F.A = 2


Both the value of the variable A and the method return value are 2.
The process is relatively simple. After the return execution in try{}, the return stream is taken to the finally child block, although the value of variable A is modified in finally, but does not affect the data in the return stream, and if finally there is a return statement, Then the return stream in the finally child block overwrites the return stream in the previous try{} and exits from the method.

If there is any mistake, please correct me.

Execution of finally blocks in Java

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.