为什么此代码不会打印“d”。为什么它没有进入RunTimeException的catch块?
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块并输出'c'。之后,因为我们没有在RuntimeException中捕获异常,所以它不再继续。但是因为保证我们转到finally块,所以打印'e'然后抛出RunttimeException。如果代码类似于以下内容,则会抛出RuntimeException(“2”)。如果我们最终在内部注释异常,它会抛出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");
}
}
答案 0 :(得分:2)
catch
块不在try
范围内。 catch
块中的任何代码都在外部main
代码的上下文中执行,因此没有异常处理程序。当你抛出RuntimeException
finally
块时,try会被执行,然后异常终止程序。
答案 1 :(得分:2)
此代码不打印d的原因是,因为在IllegalArgumentException catch块中,在打印“c”之后并且在抛出RuntimeException之前它最终执行(这就是流的工作方式)。最后块会抛出异常本身,因此它永远不会抛出使其成为“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块。 catch块只被调用一次,具体取决于try块中抛出的Exception(虽然这不是真正相关的,因为第一个解释决定了你的线程的流程)。
答案 2 :(得分:1)
在try catch块中,如果其中一个catch块捕获到异常,则其他catch不会参与。请记住,无论异常是否抛出,最终阻止总是在最后运行。