I believe everyone in the interview, or other circumstances often see such a problem, the following Inc () method call after the return value is what, the answer to everyone to carry out their own program or ask after the Niang should know, in the method is not abnormal, the return is 1, When a exception exception occurs, 2 is returned, and an exception that occurs outside exception causes the method to exit abnormally without returning a value. But this result in the virtual machine implementation principle is what, I think a lot of children's shoes are not know.
public Int Inc () {
int x;
try{
x = 1;
return x;
} catch (Exception e) {
x = 2;
return x;
} finally {
x = 3;
}
Figure 1-1
As shown in Figure 1-1, this is the byte code of the corresponding class file of the method that I obtained after executing the method with Javap-verbose
You can see from the exception table that during normal execution, is to return from step 1th to step 7th, first assigning 1 to the second local variable (step 1th-2nd), where the second local variable corresponds to x, and then the x is copied to the third local variable (3rd step-4th Step). Then execute the assignment in Finally, assign 3 to X to the second local variable, read the third local variable to the top of the Operation Stack, 1, and invoke the ireturn instruction to return as INT (step 5th-7th).
If you report exception, step 4th will follow step 8th. Assign 2 to X to the second local variable, copy 2 to fourth local variable, then execute the assignment in Finally, assign 3 to X to the second local variable, read the fourth local variable to the top of the Operation Stack, or 2, and invoke the Ireturn instruction to return as Int (step 8th-16th).
If there are other conditions, you jump directly to step 17th, assigning 3 to X to the second local variable. Pushes the exception to the top of the stack and throws it. No call to Ireturn, no return value.
Therefore, to get the above conclusions, now children's shoes know it = =
Virtual machine Byte code instruction description:
Iconst_{i}: Push int i to top of stack
Istore_{i}: Saving int value to i+1 local variable
Iload_{i}: Pushes the first i+1 int local variable to the top of the stack
Ireturn: Returning int from current method
Astore: Store the top reference value of the stack to the specified local variable
Aload: Pushes the specified reference type local variable to the top of the stack
Athrow: Throws an exception to the top of the stack