Exception
和 IOException
都是编译时检查的异常。
但是,我们不能在 catch block 中使用 IOException
。但是我们可以在 catch block 中使用 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 block 中抛出的已检查异常。此行为由 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.
关于Java 编译时检查异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32463601/