public class Starter {
public static void main(String[] args) {
System.out.println(getInt1());
System.out.println(getInt2());
}
public static int getInt1() {
int a;
// 在 try-catch 代码块中,try 中遇到 return 语句时,先把当前结果储存起来,再执行 finally 中的代码,最后才返回存储区中最新的值
// 如果 finally 中也有 return 语句,则更新存储区中的值
try {
a = 1;
// 遇到 return 语句时,将当前返回结果(即 a 的值 1)存储到临时结果区
return a;
} catch (Exception e) {
return -1;
} finally {
a = 2;
// 再次遇到 return 语句时,当前临时结果区的值更新,为 a 的新值 2
return a;
// finally 语句执行结束,返回当前临时结果区的最新值 2
}
}
public static int getInt2() {
int a;
try {
a = 1;
return a;
} catch (Exception e) {
return -1;
} finally {
a = 2;
// 因为 finally 中没有 return 语句,所以临时结果区的值没有更新,因此最后返回结果为 1
}
}
}
// 输出结果:
// 2
// 1