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块中的总是抛出是一个异常。它是catch block 1
或catch block 2
捕获的RuntimeException(未经检查的异常)或InterruptedException(检查的异常)。
但是,生成的任何未经检查的异常(编译器无法预测)都将被catch block 1
捕获。结果,catch block 3
永远不会执行。
此外,由于out.println("main ends");
块中的return
语句,行outer try
也永远不会执行。
由于程序成功编译,我的解释是错误的。
有人可以告诉我catch block 1
或out.println("main ends");
行何时执行?
import java.util.Scanner;导入静态java.lang.System.out;公共类实践{公共静态void main(String args []){Scanner sc = new Scanner(System.in); int x = sc ....
NullPointerException
是RuntimeException
的子级。因此,所有“内部尝试”块均以返回结尾。