Finally can be understood in two ways
1. Timing of implementation. Finally always executes (unless System.exit ()), normally executes after a try and throws an exception after Catche
2. The return value problem. You can assume that the return value of a return statement in a try (or catch) is placed at the top of the line stacks: If the return value is a base type, the top is the value, and if the return value is a reference type, the top holds the reference. The return statement in finally can modify the object corresponding to the reference and cannot modify the base type. However, both the base type and the reference type can be overridden by the concrete value of the finally return
3. It is not recommended to use the return statement in Finally, and if so, eclipse will warning "Finally block does not complete normally"
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162 |
package com.ljn.
base
;
/**
* @author lijinnan
* @date:2014-1-22
*/
public
class
FinallyTest {
public
static
void
main(String[] args) {
System.
out
.println(test());
System.
out
.println(testPrimitive());
}
public
static
Student test() {
Student result =
new Student(
"Tom"
, 0);
try
{
result.setAge(1);
return
result;
}
catch
(Exception e) {
result.setAge(2);
return
result;
}
finally
{
result.setAge(3);
//引用类型的返回值,可被修改
//return new Student("Kobe", 33); //可以被“具体值”覆盖
}
}
public static
int
testPrimitive() {
int
x = 0;
try
{
x = 1;
return
x;
}
catch
(Exception e) {
x = 2;
return
x;
}
finally
{
x = 3;
//基本类型的返回值,不可被修改
//return x; //可以被“具体值”覆盖
}
}
private
static
class
Student {
private
String name;
private
int age;
public
Student(String name,
int
age) {
this
.name = name;
this
.age = age;
}
@Override
public
String toString() {
return
"Student [name="
+ name +
", age=" + age +
"]"
;
}
public
void
setAge(
int
age) {
this
.age = age;
}
}
}
|
Go: Execution relationship of finally and return in Java