Finally和Return的顺序
首先finally中写return会覆盖try或者catch中的其他的return,而且finally中出现return是非常不健康的写法.(java9中会提示黄色感叹号)
try或者catch中没有return
1.try
2.catch
3.finally
catch中有return
1.try
2.catch
3.执行catch中的return,并将结果记录
<如果返回结果是基本数据类型,则记录字面量的值的拷贝,如果返回结果是引用数据类型,则记录其引用的值的拷贝>
4.执行finally
5.返回刚才记录的值
Java中,参数传递基本上就是赋值操作,所有的传递都是值传递,以下实例正好说明了这一点.
check1()中的finally没起作用是因为return的时候tempInt的值已经被return拷贝了一份了,而check2()中,return拷贝的是tempInt的地址(类似于0x1234).
public class CheckTemp {
public static void main(String[] args) {
System.out.println("整数类型返回"+check1());
System.out.println("数组类型返回"+check2()[0]);
}
public static int check1() {
int tempInt = 0;
try {
tempInt=1/0;
} catch (Exception e) {
tempInt=1;
return tempInt;
}finally {
tempInt=2;
}
return 0;//不会执行
}
public static int[] check2() {
int[] tempInt = {0};
try {
tempInt[0]=1/0;
} catch (Exception e) {
tempInt[0]=1;
return tempInt;
}finally {
tempInt[0]=2;
}
return null;//不会执行
}
}
结果
整数类型返回1
数组类型返回2