Java 编译时检查异常

Java compile time checked exception

ExceptionIOException 都是编译时检查异常。

但是,我们不能在 catch 块中使用 IOException。但是我们可以在 catch 块中使用 Exception 这是什么原因。

    import java.io.*;
    class Demo{
        public static void main(String args[]){
            try{

            }catch(IOException e){ // Does not compile

            }

            try{

            }catch(Exception e){ // Compile

            }
        }
    }

除了 Exception(或 Throwable)之外,您无法捕获从未在 try 块中抛出的已检查异常。此行为由 JLS, Section 11.2.3:

指定

It is a compile-time error if a catch clause can catch checked exception class E1 and it is not the case that the try block corresponding to the catch clause can throw a checked exception class that is a subclass or superclass of E1, unless E1 is Exception or a superclass of Exception.

回答为什么 Exception 块正在编译而 IOException 不是...只是因为一切都继承自 Exception class,它包括所有类型的异常,例如 IOException、RuntimeException 等。当您指定捕获异常时,代码中的任何内容都不一定必须将其作为运行时抛出的 RuntimeException 抛出,并且代码编译器无法预测会发生这种情况。但是 IOException 是一个特定的异常,只在某些情况下发生,因此编译器确切地知道它可能发生的时间,如果它没有检测到任何可能抛出它的代码,它就不会编译。

看,主要原因是,您可以捕获任何 RuntimeException,无论它是否从 try 块中抛出,RuntimeException 是扩展异常 class 本身的 class。因此,作为 parent class,总是允许捕获 "Exception"。在您的情况下,IOException 检查异常,只有当您尝试块有可能抛出它时才允许它。