Implementation of Return and Finally execution sequence in Java

Source: Internet
Author: User

What is the execution result of the following code?

publc int test(){int x;try{x = 1;return x;}catch(Exception e){x = 2;return x;}finally{x = 3;}}

I believe that a friend familiar with Java will immediately give the correct answer: 1 is returned normally, and 2 is returned if an exception occurs. When I saw this code for the first time, I had doubts about x = 3 in finally, and I was not sure whether the final returned x was changed to 3, it was not until the bytecode of this code was found in the deep understanding of Java virtual machine that it understood its operating mechanism. The following is the bytecode of the above Java code:

Public int test (); Code: Stack = 1, Locals = 5, Args_size = 1 0: iconst_1 // write 1 to the top 1 of the Stack: istore_1 // write the top value of the stack (1) to 2nd int local variables; 2: iload_1 // load 2nd int local variables to the top of the stack (start of Return Statement) 3: istore 4 // Save the stack top value to 4th int local variables. At this time x = 1 5: iconst_3 // write 3 to the stack top (Finally started) 6: istore_1 // write 3 to 2nd int local variables 7: iload 4 // laod the value of 4th int local variables to the Top 9 of the stack: ireturn // return the stack top value 10: astore_2 11: iconst_2 12: istore_1 13: iload_1 14: istore 4 16: iconst_3 17: istore_1 18: iload 4 20: ireturn 21: astore_3 22: iconst_3 23: istore_1 24: aload_3 25: athrow

From the bytecode above, the Return Statement is divided into two parts: istore 4 and iload 4 & ireturn. The finally code is inserted between store and load, the value of x is first stored in a specified position and then executed in the finally statement. In this case, the code in finally cannot affect the return value.

Related Article

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.