为什么这段代码不打印“d”。为什么它不进入 RunTimeException 的 catch block ?
public static void main(String[] args) {
System.out.println("a");
try {
System.out.println("b");
throw new IllegalArgumentException();
} catch (IllegalArgumentException e) {
System.out.println("c");
throw new RuntimeException();
}catch (RuntimeException e) {
System.out.println("d");
throw new RuntimeException();
}finally{
System.out.println("e");
throw new RuntimeException();
}
}
该程序的输出是
a
b
c
e
Exception in thread "main" java.lang.RuntimeException
编辑:抛出 IllegalArgumentException 后,它会转到相应的 catch block 并打印“c”。之后,由于我们没有捕获 RuntimeException 中的异常,因此不会再进一步。但由于保证我们进入finally block ,所以它会打印“e”,然后抛出RunttimeException。如果代码如下所示,它将抛出 RuntimeException("2")。如果我们在finally中注释异常,它会抛出RuntimeException(“1”)。
public static void main(String[] args) throws InterruptedException {
System.out.println("a");
try {
System.out.println("b");
throw new IllegalArgumentException();
} catch (IllegalArgumentException e) {
System.out.println("c");
throw new RuntimeException("1");
}catch (RuntimeException e) {
System.out.println("d");
throw new RuntimeException();
}finally{
System.out.println("e");
throw new RuntimeException("2");
}
}
最佳答案
此代码不打印 d 的原因是,因为在 IllegalArgumentException catch block 中,在打印“c”之后、抛出 RuntimeException 之前,它最终执行(这就是流程的工作原理)。 Final block 本身会抛出异常,因此它永远不会抛出使其变为“d”的 RuntimeException。
public static void main(String[] args) {
System.out.println("a");
try {
System.out.println("b"); // 1
throw new IllegalArgumentException(); // 2
} catch (IllegalArgumentException e) {
System.out.println("c"); // 3
throw new RuntimeException(); // nope, there's a finally block that executes first
}catch (RuntimeException e) {
System.out.println("d");
throw new RuntimeException();
}finally{
System.out.println("e"); // 4
throw new RuntimeException(); // 5 - rest of the code never got executed.
}
}
希望这足够清楚。
此外,正如所指出的,即使“c”之后的 RuntimeException 被执行,它也不会调用较低的 catch block 。 catch block 仅被调用一次,具体取决于 try block 中抛出的异常(尽管这并不真正相关,因为第一个解释决定了线程的流程)。
关于java - 异常链在我的代码中如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35387305/