Execution order resolution for finally and return in Java (code example)

Source: Internet
Author: User
This article brings you the content is about the Java finally and return execution order resolution (code example), there is a certain reference value, the need for friends can refer to, I hope to help you.

All know, finally the execution characteristics

1, regardless of the occurrence of wood anomalies, finally block code will be executed;

2. Finally will still execute when there is a return in the try and catch.

So the question is, what is the order of execution?

A simple test class and a post-compilation bytecode:

public class Test {publicstatic void main (string[] args) {System.out.println (test ()); } publicstatic int Test () {try{System.out.println ("Codesin try Blo                            ck. ");                   Return0;                            }catch (Exception e) {System.out.println ("Codesin catch block.");                   return100;                   }finally {System.err.println ("Codesin finally block.");   }}}/* public static int test ();      code:0: getstatic #2//Fieldjava/lang/system.out:ljava/io/printstream;      3:LDC #5//String Codes in try block. 5:invokevirtual #6//Method java/io/printstream.println: (ljava/lang/string;) V 8:iconst_0 9:i     Store_0 10:getstatic #7//Field Java/lang/system.err:ljava/io/printstream; 13: LDC #8//String Codes in Finallyblock. 15:invokevirtual #6//Method java/io/printstream.println: (ljava/lang/string;) V 18:iload_0 19:i     return 20:astore_0 21:getstatic #2//Fieldjava/lang/system.out:ljava/io/printstream;     24:LDC #10//String Codes in Catchblock.      26:invokevirtual #6//Method java/io/printstream.println: (ljava/lang/string;) V 29:bipush 100     31:istore_1 32:getstatic #7//Fieldjava/lang/system.err:ljava/io/printstream;     35:LDC #8//String Codes in Finallyblock. 37:invokevirtual #6//Method java/io/printstream.println: (ljava/lang/string;) V 40:iload_1 41:i     return 42:astore_2 43:getstatic #7//Fieldjava/lang/system.err:ljava/io/printstream; 46:LDC #8//String Codes in Finallyblock. 48:invokevirtual #6//Method java/io/printstream.println: (ljava/lang/string;) V 51:aload_2 52:a throw*/

We can compare the code we write with the compiled bytecode:

Discovering that the virtual machine did a lot for us, it inserted the finally statement block between the Try,catch and the return statement. This is why the finally will be executed regardless of whether the exception is returned or not. Now that the finally is executed, return what is in the finally. Since finally all return is invalid, what is the meaning of return, so the actual finally block is not allowed to return. The eclipse compiler prompts Warning:finallyblock does not to complete normally.

Test code for several scenarios

try{return;} catch () {} finally{} return;

Test code:

1. Basic data types

   public static int test1 () {      int a = ten;      try{         a =;         return A;      } catch (Exception e) {         //other codes.      } finally{         A + = 5;         Other codes.      }      return A;   } The final return value is 20

2. Reference data type changes the value of the referenced object

   public static StringBuffer Test2 () {      StringBuffer sb = new StringBuffer ("abc");      try{         return sb;      } catch (Exception e) {         //other codes.      } finally{         sb.append ("DEF");         Other codes.      }      return SB;   } The content of the final return is abcdef
  public static StringBuffer Test3 () {      StringBuffer sb = new StringBuffer ("abc");      try{         return sb;      } catch (Exception e) {         //other codes.      } finally{         sb = new StringBuffer ("DEF");         Other codes.      }      return SB;   } The content in the final return value is ABC

In this case, it can be found that, before finally, if there is a return statement, finally on the return variable no matter what changes, the variable itself will not be changed, such as for the basic type of variable re-assignment, or for the reference type of the variable to re-specify the reference is not recorded in the return value. But the statement in finally executes, and in finally, the object content to which the reference type's variable points is modifiable, and the modification is valid. This situation can be understood, encountered a return statement, the virtual machine to return the value of a set of houses, the house can be arbitrarily dismantled? No. But the people inside the house can change. The variables of the base data type and the reference type are the houses themselves, and the contents of the objects to which the reference type variable points are the people in the house.

There is such a small test:

   public static int test (int num) {      int a = ten;      try{         return A;      } catch (ArithmeticException e) {         a =;         return A;      } finally{         a = +;         return A;      }   }

What is the return value when there is no exception in the 1.1 try block?

What is the return value when there is a ArithmeticException exception in the 1.2 try block?

What is the return value when there are other exceptions in the 1.3 try block?

Answer: All 30. The reason is that after executing the code before return in the try block, the JVM inserts the code in the finally block between return and the finally block contains a return, then it returns directly.

Related Article

Beyond APAC's No.1 Cloud

19.6% IaaS Market Share in Asia Pacific - Gartner IT Service report, 2018

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.