Exception thrown in catch and finally clause

since: 2016-12-14 21:32:51

一个有趣的问题,如果在catch或是finally里面抛出异常,会发生什么呢

Question

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public static void main(String[] args) throws Exception {
try {
System.out.println("begin");
tryThrow();
} catch (Exception e) {
throw new Exception("ex3");
} finally {
System.out.println("main throw");
throw new Exception("ex4");
}
}

private static void tryThrow() throws Exception {
try {
throw new Exception("ex1");
} catch (Exception e) {
//ignore
} finally {
System.out.println("try throw");
throw new Exception("ex2");
}
}

Answer

1
2
3
4
5
begin
try throw
main throw
Exception in thread "main" java.lang.Exception: ex4
at line;
  • 每当抛出一个异常,都会离开当前代码块,例如 try -> catch -> finally
  • 每当抛出一个异常,上一个异常会立刻结束,并展开新异常的堆栈

Resources

Exception thrown in catch and finally clause – stackOverFlow
Oracel docs

喜欢的大佬,路过赏点儿呗~