[英]Why such output is coming?
这可能很容易,但我不明白为什么输出为1 4.而第9行的return语句的功能是什么?
public static void main(String[] args) {
try{
f();
} catch(InterruptedException e){
System.out.println("1");
throw new RuntimeException();
} catch(RuntimeException e){
System.out.println("2");
return; \\ Line 9
} catch(Exception e){
System.out.println("3");
} finally{
System.out.println("4");
}
System.out.println("5");
}
static void f() throws InterruptedException{
throw new InterruptedException("Interrupted");
}
提前致谢。
你的function f()
抛出InterruptedException
,它被第一个catch块捕获(因此它打印1),但是这个catch块不能抛出其他异常(如果它没有被你的方法抛出),因此,没有其他catch块可以捕获你的感知因此最终被执行(最终在除了那些愚蠢的无限循环案例之外的所有情况下执行)。 你可以参考catch块中抛出的异常 - 它会被再次捕获吗? 。
我希望它有所帮助。
总结一下,你可以从try块中抛出任何异常并将它捕获(如果有一个好的catch块)。 但是从catch块中,只有那些异常可以抛出(并因此被捕获),你的方法抛出了这些异常。
如果你从catch块中抛出异常而不是你的方法抛出的异常,那就意味着更少并且不会被捕获(就像你的情况一样)。
正如你所看到的那样, f()
会抛出InterruptedException,所以它会首先打印1 ,它位于第一个catch块内,然后最终执行,因此它将打印4 。
打印1是因为f()
抛出InterruptedException。 因为异常是在第一个catch块中处理的,所以不再在其他异常块中处理它。 finally语句始终运行,因此也打印4。
try{
f();
} catch(InterruptedException e){
System.out.println("1");
throw new RuntimeException(); // this RuntimeException will not catch by
//following catch block
} catch(RuntimeException e){
您需要按如下方式更改代码才能捕获它。
try{
f();
} catch(InterruptedException e){
System.out.println("1");
try {
throw new RuntimeException();// this RuntimeException will catch
// by the following catch
}catch (RuntimeException e1){
System.out.println("hello");
}
} catch(RuntimeException e){
System.out.println("2");
return;
} catch(Exception e){
System.out.println("3");
} finally{
System.out.println("4");
}
System.out.println("5");
然后你的出局“
1
hello // caught the RunTimeException
4 // will give you 2,but also going to finally block then top element of stack is 4
5 // last print element out side try-catch-finally
f()
抛出一个InterruptedException
所以你得到1
。 终于总是在最后调用,所以你得到了4
。
当f()抛出执行的InterruptedException,
catch(InterruptedException e){
System.out.println("1");
throw new RuntimeException();
}
打印 - > 1
最后在退出程序之前执行,
finally{
System.out.println("4");
}
打印 - > 4
返回后的代码不会执行但最终会被执行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.