<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">欢迎转载、转载请注明出处 <a target=_blank href="http://http://blog.csdn.net/aizanhao">http://blog.csdn.net/aizanhao</a></span>
1、没有异常时,执行顺序:1-->2-->5-->3;
执行完1之后,会执行return后面的表达式2(也就是返回值,此时返回值会赋给另一个局部变量(假设为backValue)存放在内存中),之后执行finally中的5,最后执行3(return backValue 而不是 return x)。finally中的代码改变了x的值,但是不会改变返回值。
<span style="font-size:18px;">public class Demo {
public static void main(String args[]) {
System.out.println("返回值 x:" + new Demo().test());
}
public int test(){
int x = 1;
try{
return x;
} finally{
++x;
System.out.println("finally executed: x=" + x);
}
}
}</span>
结果:finally executed: x=2返回值 x:1
finally在return之前执行,finally改变了x的值,但是没有改变返回值,返回值在finally执行之前已经保存在内存中。
2、有异常时,执行顺序:1-->4-->6-->5-->7;
<span style="font-size:18px;">public class Demo {
public static void main(String args[]) {
System.out. println ("返回值x:" + new Demo().test());
}
public int test() {
int x = 1;
int y;
try {
y = 1/0;
return x;
} catch (Exception e) {
return ++x;
} finally {
++x;
System.out.println("finally executed: x=" + x);
}
}
}</span>
结果:finally executed: x=3返回值x:2
y=1/0有异常,直接跳到catch中,和情况1类似,先计算返回值(++x=2)存放在内存中,然后再执行finally(只改变x的值,不改变返回值,因为返回值已经存放在内存中),最后执行return,将内存中的返回值返回。
3、finally 中有 return
<span style="font-size:18px;">public class Demo {
public static void main(String args[]) {
System.out. println ("返回值x:" + new Demo().test());
}
public int test() {
int x = 1;
int y;
try {
y = 1/0;
return x;
} catch (Exception e) {
return ++x;
} finally {
++x;
System.out.println("finally executed: x=" + x);
return 8000;
}
}
}
</span>
结果:
finally executed: x=3
返回值x:8000
结论:
1、不管有没有异常,try和catch中有没有return,finally都会执行。
2、finally不会影响返回值,返回值在进入finally之前已经确定,存放在内存中。
3、finally是在return表达式之后执行(此时,返回值=(表达式的值)已经存放在内存中),执行完finally之后,最后:return返回值。