考虑以下四个测试方法,它们会输出什么?
public class Test {
public static void main(String\[\] args) {
System.out.println(test1());
System.out.println(test2());
System.out.println(test3());
System.out.println(test4());
}
private static int test1() {
int i = 1;
try {
return i;
} catch (Exception e) {
e.printStackTrace();
} finally {
i = 0;
}
return i;
}
private static int test2() {
int i = 1;
try {
return i;
} catch (Exception e) {
e.printStackTrace();
} finally {
i = 0;
return i;
}
}
private static User test3() {
User user = new User("u1");
try {
return user;
} catch (Exception e) {
e.printStackTrace();
} finally {
user = new User("u2");
}
return null;
}
private static User test4() {
User user = new User("u1");
try {
return user;
} catch (Exception e) {
e.printStackTrace();
} finally {
user.setName("u2");
}
return null;
}
}
public class User {
public User(String name) {
this.name = name;
}
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
}
答案如下:
1
0
u1
u2
结论
1、不管try,finally都会执行;
2、在try中return,在finally执行前会把结果保存起来,即使在finally中有修改也以try中保存的值为准,但如果是引用类型,修改的属性会以finally修改后的为准;
3、如果try/finally都有return,直接返回finally中的return。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。