try/catch的用法我们都很熟悉,finally关键字也常与该代码块配合使用,用于申明无论是否捕获到异常都会执行的语句。我们分为以下几种情况测试以下finally语句对程序执行的影响:
(1)返回值为基本数据类型:
class A{
//finally中对返回值做修改但不返回
public int test1(){
int i = 0;
try {
return i;
}catch (Exception e){
e.printStackTrace();
}finally {
i = 1;
}
return i;
}
//finally中对返回值做修改且返回
public int test2(){
int i = 0;
try {
return i;
}catch (Exception e){
e.printStackTrace();
}finally {
i = 1;
return i;
}
}
}
public class Test {
public static void main(String[] args){
System.out.println(new A().test1());
System.out.println(new A().test2());
}
}
//测试结果:
0
1
(2)返回值为引用类型:
class B{
String str = "abc";
}
class A{
B b = new B();
//finally修改返回值的成员但不返回
public B test1(){
try {
return this.b;
}catch (Exception e){
e.printStackTrace();
}finally {
this.b.str = "def";
}
return this.b;
}
//finally修改返回值的成员且返回
public B test2(){
try {
return this.b;
}catch (Exception e){
e.printStackTrace();
}finally {
this.b.str = "def";
return this.b;
}
}
}
public class Test {
public static void main(String[] args){
System.out.println(new A().test1().str);
System.out.println(new A().test2().str);
}
}
//测试结果:
def
def
通过以上测试我们可以得出以下结论:
1、不管try,finally都一定会执行;
2、在try中return,在finally执行前会把结果保存起来,即使在finally中有修改也以try中保存的值为准,但如果是返回值
是引用类型,修改的属性会以finally修改后的为准;
3、如果try/finally都有return,直接返回finally中的return。