gpt4 book ai didi

java - 为什么不是遥不可及呢?

转载 作者:行者123 更新时间:2023-12-01 19:32:54 24 4
gpt4 key购买 nike

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 1catch block 2 捕获的 RuntimeException(未经检查的异常)或 InterruptedException(检查的异常)。

任何生成的未经检查的异常(编译器未预测到的)都将被 catch block 1 捕获。因此,catch block 3 永远不会被执行。

此外,由于 outer try 中的 return 语句,out.println("mainends"); 行也永远不会被执行> 阻止。

我的解释是错误的,因为程序编译成功。

有人可以告诉我 catch block 1out.println("mainends"); 行什么时候执行吗?

最佳答案

NullPointerExceptionRuntimeException 的子级。因此,所有“内部尝试” 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com