try…catch…finally中的引用传递
public class Demo01 {
public Student add(Student stu) {
try {
return stu;
} catch (Exception e) {
} finally {
stu.setAge(20);
}
return null;
}
public static void main(String[] args) {
Demo01 demo01 = new Demo01();
Student student = new Student();
student.setAge(18);
Student rs = demo01.add(student);
System.out.println(rs.getAge());
}
}
结果:20
输出20的原因:因为这里demo01.add(student);
传的student是引用传递,传递的是student在内存中的地址,但是因为有try...catch...finally
,所以add
方法返回的还是student在内存中的地址,但是finally
的原因,已经将student这个地址的内存中的数据进行了修改,不管你是不是执行完finally后在返回这一套了。
try…catch…finally中的值传递
public class Demo02 {
public int add() {
int c = 0;
try {
return c = 1;
} catch (Exception e) {
System.out.println("catch语句块");
} finally {
c = 2;
System.out.println("finally语句块");
}
return 0;
}
public static void main(String[] args) {
Demo02 demo01 = new Demo02();
int rs = demo01.add();
System.out.println("c是:" + rs);
}
}
结果:c是:1
要注意的是:如果有try...catch...finally
的话,finally
不管在什么情况下都要被先执行,哪怕你try
或者catch
中有return
,也要执行完finally
中的内容。