以前的笔记,今天面试被问到,有点模糊了,重新整理一下
package BasicKnowlege;
public class TryCatchTest {
public static void main(String[] args){
System.out.println(testMethod());
}
private static int testMethod(){
try {
int i = 1;
System.out.println("try:"+i);
//1
return i;
}catch (Exception e){
int i = 2;
System.out.println("catch:"+i);
//2
return i;
}finally {
int i = 3;
System.out.println("finally:"+i);
//3
return i;
}
//4
// return 0;
}
}
/**
* 上面的情况:
* (1)1、2、3、4均注销,
* 没有异常,会执行try和finally中的语句
* 有异常,执行catch和finally中的语句
* (2)只有1开启,或者1、4开启,会返回try中的i。输出 try:1 finally:3 1(忽略回车)
* 1、3开启,会只返回finally中的i,输出try:1 finally:3 3(忽略回车)
* 2、3开启,同上。
* 原因:在执行完try/catch中的语句后,返回值会先存在局部面量表里面
* ,继续执行完finally后,在输出try/catch中的返回值。
* 如果finally中有返回值,就直接结束,不会再返回输出try/catch中的返回值。
* (3)3、4不能重复开启,会出现多余的返回值。编译器提示Unreachable statement
* 参考个人凌乱的笔记:https://docs.qq.com/doc/Bc91Pm28K4Sh0MXl8D4jVe5R1yECQJ3hsfMC3
**/