本文内容关于Java异常处理执行顺序问题
一、原理讲解
二、代码实例
public class ReturnExceptionDemo {
static void methodA() {
try {
System.out.println("进入方法A");
throw new RuntimeException("制造异常");
} finally {
System.out.println("用A方法的finally");
}
}
static int methodB() {
try {
System.out.println("进入方法B");
// throw new Exception(); 注释A
return 1;
} catch (Exception e) {
return 3;
} finally {
System.out.println("调用B方法的finally");
// return 2; 注释B
}
}
public static void main(String[] args) {
try {
methodA();
} catch (Exception e) {
System.out.println(e.getMessage());
}
int i = methodB();
System.out.println(i);
}
}
这里methodA比较简单,需要注意的是methodB。
methodB里有两个注释A和B,这里分别讲一下
- 注释A的地方不可以加上,否则抛出异常后的代码都不会被执行
- 注释B中,finally中的语句会在try中return执行前执行,所以如果注释B执行的话,返回值会变成2