编译器如何识别永远不会从java中的try语句主体抛出异常

nam*_*olk 3 java exception

当我抓住ParseException(代码1)时,编译器会喊" Unreachable catch block for ParseException. This exception is never thrown from the try statement body".但当我赶上Exception(代码2)时,它是一个愚蠢的.为什么是这样?

代码1:

try {
    int i = 0;
}catch (ParseException e1) { //Unreachable catch block for ParseException. This exception is never thrown from the try statement body
    e1.printStackTrace();   
}
Run Code Online (Sandbox Code Playgroud)

代码2:

try {
    int i = 0;
}catch (Exception e2) { // ............. (dumbed???)
    e2.printStackTrace();   
}
Run Code Online (Sandbox Code Playgroud)

注意:我在其他地方意外地注意到了这一点.上面只是一个模拟的例子.

rue*_*ste 8

原因很简单.分配整数可能导致StackOverflowException,或者当前线程可能被中断(导致InterruptedException).两者都是Exception的子类,因此可以被捕获.

另一方面,ParseException是一个经过检查的异常,您的代码无法抛出该异常.因此无法到达的捕获块.

在此输入图像描述