上代码
public class TryTest {
public static void main(String... args) {
System.out.println(m1());
}
static int m1() {
int x;
try {
x = 1;
return x;
} catch (Exception e) {
x = 2;
return x;
} finally {
x = 3;
}
}
}
结果
因为在执行try语句块时return已经把x的值1读入到了栈顶,在finally语句块中再把x的值赋值3,语句执行完毕,返回栈顶的值‘1’;
如果在finally语句块中加入 return x;
public class TryTest {
public static void main(String... args) {
System.out.println(m1());
}
static int m1() {
int x;
try {
x = 1;
return x;
} catch (Exception e) {
x = 2;
return x;
} finally {
x = 3;
return x;
}
}
}
结果
无论变量结果是啥,最后返回的是栈顶的值;
结论
1. 如果try语句块中出现Exception的异常或其子类异常,则转到catch语句块处理。
2. 如果try语句块中不出现Exception的异常或其子类异常,则转到finally语句块处理。
3. 如果catch语句块出现异常,则转到finally语句块。