作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
import java.util.Scanner;
import static java.lang.System.out;
public class practice
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int x=sc.nextInt();
try //outer try
{
try //inner try
{
if(x==1)
throw new NullPointerException();
else if(x==2)
throw new InterruptedException();
else
throw new RuntimeException();
}
catch(RuntimeException e) //catch block 1
{
out.println("RuntimeException caught!");
}
catch(InterruptedException e) //catch block 2
{
out.println("InterruptedException caught!");
}
out.println("inner try ends");
return;
}
catch(Exception e) //catch block 3
{
out.println("Exception caught!");
}
finally
{
out.println("from finally");
}
out.println("main ends"); //unreachable code?
}
}
在上面的代码中,内部 try block 总是抛出异常。它是由 catch block 1
或 catch block 2
捕获的 RuntimeException(未经检查的异常)或 InterruptedException(检查的异常)。
任何生成的未经检查的异常(编译器未预测到的)都将被 catch block 1
捕获。因此,catch block 3
永远不会被执行。
此外,由于 outer try
中的 return
语句,out.println("mainends");
行也永远不会被执行> 阻止。
我的解释是错误的,因为程序编译成功。
有人可以告诉我 catch block 1
或 out.println("mainends");
行什么时候执行吗?
最佳答案
NullPointerException
是 RuntimeException
的子级。因此,所有“内部尝试” block 都以返回结束。
out.println("inner try ends");
---> return;
所有的finally block 都被执行为docs说:
The finally block always executes when the try block exits.
在这种情况下,return结束了“外部尝试”,并且finally被执行。
如果你让你的代码更简单,你会注意到最后一个打印是无法访问的:
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
try {
try {
if (x == 1) {
throw new NullPointerException();
}
} catch (NullPointerException e) {
}
return;
} finally {
out.println("from finally");
}
out.println("main ends");
}
Main.java:24: error: unreachable statement
out.println("main ends");
^
关于java - 为什么不是遥不可及呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59025081/
我是一名优秀的程序员,十分优秀!