测试代码:
package com.yucq.JavaSE.unknown;
/*
面试题: try, catch, finally中都有return, 最后会返回谁的return?
答:
无论是否抛异常(无论是在try中还是在catch中return), finally中的代码都会被执行.
try, catch中return的值, 会先保存在一个局部变量中.
再执行finally中的代码.
如果finally中有return, 会修改这个局部变量, 如果没有, 则不会.
ps:
不建议在finally中写return. 虽然编译器让通过, 但是会给警告的.
但, 谁没事会在finally中写return啊?
*/
/*
If the try clause executes a return, the compiled code does the following:
1. Saves the return value (if any) in a local variable.
2. Executes a jsr to the code for the finally clause.
3. Upon return from the finally clause, returns the value saved in the local variable.
(以下机翻)
如果 try 子句执行返回,则编译后的代码会执行以下操作:
1. 将返回值(如果有)保存在局部变量中。
2. 对 finally 子句的代码执行 jsr。
3. 从 finally 子句返回时,返回保存在局部变量中的值。
*/
public class DemoReturn {
public static void main(String[] args) {
System.out.println("---finally中有return---");
System.out.println(test1());
System.out.println("------");
System.out.println(test2());
System.out.println("---finally中没有return---");
System.out.println(test3());
System.out.println("------");
System.out.println(test4());
}
/**
* finally中有return
* finally中的return会覆盖try, catch中的return
*/
public static int test1() {
// 不抛异常
int i = 1;
try {
i++;
System.out.println("try" + i);
return i;
} catch (Exception e) {
i++;
System.out.println("catch" + i);
return i;
} finally {
i++;
System.out.println("finally" + i);
return i;
}
}
public static int test2() {
// 抛异常
int i = 1;
try {
int a = 1 / 0;
i++;
System.out.println("try" + i);
return i;
} catch (Exception e) {
i++;
System.out.println("catch" + i);
return i;
} finally {
i++;
System.out.println("finally" + i);
return i;
}
}
/**
* finally中没有return
*/
public static int test3() {
// 不抛异常
int i = 1;
try {
i++;
System.out.println("try" + i);
return i;
} catch (Exception e) {
i++;
System.out.println("catch" + i);
return i;
} finally {
i++;
System.out.println("finally" + i);
System.out.println("i的值已经被拷贝出来一份存到返回值里面了, 再修改i不会改变返回值. 除非finally中有return.");
}
}
public static int test4() {
// 抛异常
int i = 1;
try {
int a = 1 / 0;
i++;
System.out.println("try" + i);
return i;
} catch (Exception e) {
i++;
System.out.println("catch" + i);
return i;
} finally {
i++;
System.out.println("finally" + i);
}
}
}
输出结果:
---finally中有return---
try2
finally3
3
------
catch2
finally3
3
---finally中没有return---
try2
finally3
i的值已经被拷贝出来一份存到返回值里面了, 再修改i不会改变返回值. 除非finally中有return.
2
------
catch2
finally3
2
进程已结束,退出代码0