1. 如果 finally 中没有 return,try和catch中第一个执行的 return作为返回值。(当返回值是可变对象时 finally 中的代码可以修改返回对象的值,比如 a.b=1,但已经不能修改返回对象的地址指向,比如 a = new A1())
2. 如果 finally 中有 return,try和catch中的 return 只起到阻止后续代码执行的作用,返回值以 finally 中的 return 为准。
3. try 和 catch 中的 return 会阻止后续代码的执行,但不会阻止 finally 中代码的执行。
============================
public class A1 {
static A1 a = new A1();
static int x1 = 10;
private int b = 1;
public static void main(String[] args) throws Exception {
System.out.println("testA().b===" + testA().b);
System.out.println("testB()===" + testB());
}
public static A1 testA() throws InterruptedException {
try {
int y1 = 1 / 0;
return a;
} catch (RuntimeException e) {
a.b = 2;
return a;
} finally {
a.b = a.b + 2;
}
}
public static int testB() throws Exception {
try {
x1 = x1 + 5;
x1 = x1 / 0;
return x1;
} catch (RuntimeException e) {
x1 = x1 + 5;
return x1;
} finally {
x1 = x1 + 5;
}
}
}