我创建了一个自定义异常类,如下所示
public class CustomException extends Exception{
// some code here
}
Run Code Online (Sandbox Code Playgroud)
现在我有一段代码如下
File file = new File("some_file_path");
try {
FileOutputStream outputStream = new FileOutputStream(file);
} catch (CustomException e) {
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
但编译器显示错误未处理的异常类型FileNotFoundException
我的观点是编译器是否理解我通过CustomException捕获FileNotFoundException?
请帮忙.
FileNotFoundException是IOException其子类是Exception的子类.
层次结构 -
java.lang.Throwable
java.lang.Exception
java.io.IOException
java.io.FileNotFoundException
Run Code Online (Sandbox Code Playgroud)
并且CustomException是Exception层次结构的子类-
java.lang.Throwable
java.lang.Exception
java.io.CustomException
Run Code Online (Sandbox Code Playgroud)
显然CustomException不是异常的链条,这是不是超一流的既不IOException也没有 FileNotFoundException,这就是为什么你不能赶上FileNotFoundException用CustomException.
但是你可以赶上FileNotFoundException与IOException,Exception和Throwable除外FileNotFoundException.