题目一、
public class Test {
public static void main(String[] args) {
System.out.println(test());
}
public static int test() {
try {
return 1;
} catch (Exception e) {
return 2;
} finally {
System.out.print("3");
}
}
}
//输出:
31
try、catch、finally 的基础用法,在 return 前会先执行 finally 语句块,所以会先输出 finally 里的 3,再输出 return 的 1。由于这里try中没有异常发生,因此catch中的return不会执行
题目二、
public class Test {
public static void main(String[] args) {
System.out.println(test());
}
public static int test() {
try {
int i = 1/0;
return 1;
} catch (Exception e) {
return 2;
} finally {
System.out.print("3");
}
}
}
//输出:
32
在 return 前会先执行 finally 语句块,所以会先输出 finally 里的 3,再输出 catch 中 return 的 2。由于这里try中有异常发生,因此try后续语句不会再执行
题目三、
public class Test {
public static void main(String[] args) {
System.out.println(test());
}
public static int test() {
try {
return 2;
} finally {
return 3;
}
}
}
//输出:
3
try中的return前先执行 finally,结果 finally 直接 return 了,自然也就走不到 try 里面的 return 了。
题目四、
public class Test {
public static void main(String[] args) {
System.out.println(test());
}
public static int test() {
int i = 0;
try {
i = 2;
return i;
} finally {
i = 3;
}
}
}
//输出:
2
在执行 finally 之前,JVM 会先将 i 的结果暂存起来,然后 finally 执行完毕后,会返回之前暂存的结果,而不是返回 i,所以即使 i 已经被修改为 3,最终返回的还是之前暂存起来的结果 2。
总结
- 无论try中是否有return,是否有异常,finally都一定会执行。
- 如果try中有异常发生,会执行catch中的句子,try中异常后续的位置的语句不会再被执行
- 当try与finally语句中均有return语句,会忽略try中return。
- try中有return, 会先将值暂存,无论finally语句中对该值做什么处理,最终返回的都是try语句中的暂存值。