通过简单例题快速掌握try catch finally返回值顺序
观察以下代码:
public class Text01 {
public static void main(String args[]) {
test();
}
public static void test() {
int temp=1;
try {
System.out.println(temp);
}catch(Exception e) {
System.out.println(temp);
}finally {
++temp;
System.out.println(temp);
}
}
}
运行结果如下:
以上代码未出现异常,执行完try语句后直接执行finally语句,输出1后变量temp自加为2并输出。
接下来再看一道题:
public class Text02 {
public static void main(String args[]) {
System.out.println(test()+"x");
}
public static int test() {
int temp=1;
try {
System.out.println(temp+"y");
return ++temp;
}catch(Exception e) {
System.out.println(temp);
return ++temp;
}finally {
++temp;
System.out.println(temp+"z")
}
}
}
答案如下:
此题的执行步骤为:
1、调用test()方法
2、执行try块里的内容,输出1y,变量temp的值自加为2并储存在变量域和返回值域中
3、未发现异常,不执行catch块里内容
4、执行finally块中的语句,temp自加为3并保存在变量域中,输出3z
5、test()方法执行完毕,返回保存在返回值域中的内容
6、返回值域中temp的值为2,不受finally块里语句的影响,输出2x
此题加在try和catch里加入了return语句,观察运行结果发现在finally中temp的自加操作并未改变temp的返回值,由此可得结论函数的返回值是在finally块执行前确定的,不论在finally块如何改变返回值,函数返回值都不会发生改变。
但如果在finally里加入返回值,那么返回值就会被改变:
public class Text03 {
public static void main(String args[]) {
System.out.println(test());
}
public static int test() {
int temp=1;
try {
return temp;
}catch(Exception e) {
System.out.println(temp);
return ++temp;
}finally {
++temp;
return temp;
}
}
}
运行结果:
在函数未返回try中的temp值时fianlly就已经返回,函数相当于更新返回值域里temp的值并提前结束,所以在temp自加为2后直接返回,输出2。