1. 不带 return 的执行顺序
异常处理中,try、catch 、finally 的执行顺序:
- 如果 try 中没有异常,执行顺序为:try —> finally
- 如果 try 中有异常,执行顺序为:try —> catch —> finally
public class Test {
public static int rank;
public static void main(String[] args) {
rank = 1;
solve2();
System.out.println("over");
}
public static void solve1() throws Exception {
try {
System.out.println("solve 1 try, rank: " + rank++);
throw new Exception("throw by solve 1");
} finally {
System.out.println("solve 1 finally, rank: " + rank++);
}
}
public static void solve2() {
try {
System.out.println("solve 2 try, rank: " + rank++);
solve1();
} catch (Exception e) {
System.out.println("catch exception: " + e.getMessage() + ", rank: " + rank++);
} finally {
System.out.println("solve 2 finally, rank: " + rank++);
}
}
}
// solve 2 try, rank: 1
// solve 1 try, rank: 2
// solve 1 finally, rank: 3
// catch exception: throw by solve 1, rank: 4
// solve 2 finally, rank: 5
// over
首先是 try 执行,如果发生异常,那就直接捕获异常,最后执行 finally。但是,如果抛出异常,例如在 solve1 方法中,throw 了一个异常,那么不会立刻回溯到上一方法,而是仍然执行 finally。
2. 带 return 的执行顺序
2.1 try 中带 return 的
基本类型:
public class Test {
public static void main(String[] args) {
System.out.println(testReturn());
}
public static int testReturn() {
int i = 1;
try {
i++;
System.out.println("try: " + i);
return i;
} catch (Exception e) {
i++;
System.out.println("catch: " + i);
} finally {
i++;
System.out.println("finally: " + i);
}
return i;
}
}
// try: 2
// finally: 3
// 2
引用类型:
public static void main(String[] args) {
System.out.println(testReturn2());
}
public static List<Integer> testReturn2() {
List<Integer> list = new ArrayList<>();
try {
list.add(1);
System.out.println("try: " + list);
return list;
} catch (Exception e) {
list.add(2);
System.out.println("catch: " + list);
} finally {
list.add(3);
System.out.println("finally: " + list);
}
return list;
}
// try: [1]
// finally: [1, 3]
// [1, 3]
2.2 catch 中带 return 的
public static void main(String[] args) {
System.out.println(testReturn3());
}
public static int testReturn3() {
int i = 1;
try {
i++;
System.out.println("try: " + i);
int x = i / 0;
} catch (Exception e) {
i++;
System.out.println("catch: " + i);
return i;
} finally {
i++;
System.out.println("finally: " + i);
}
return i;
}
// try: 2
// catch: 3
// finally: 4
// 3
2.3 finally 中带 return 的
public static void main(String[] args) {
System.out.println(testReturn4());
}
public static int testReturn4() {
int i = 1;
try {
i++;
System.out.println("try: " + i);
return i;
} catch (Exception e) {
i++;
System.out.println("catch: " + i);
} finally {
i++;
System.out.println("finally: " + i);
return i;
}
}
//try: 2
//finally: 3
//3
- finally 中的代码总会执行
- 当 try、catch 中有 return 时,也会执行 finally。return 的时候,要注意返回值的类型,是否收到 finally 中代码的影响
- finally 中有 return 时,会直接在 finally 中退出,导致 try、catch 中的 return 失效
参考
https://www.cnblogs.com/pcheng/p/10968841.html
https://blog.csdn.net/iwts_24/article/details/88849690
https://blog.csdn.net/cockroach02/article/details/80186723