我创建了一个自定义异常类,如下
public class CustomException extends Exception{
// some code here
}
现在我有一段代码如下
File file = new File("some_file_path");
try {
FileOutputStream outputStream = new FileOutputStream(file);
} catch (CustomException e) {
e.printStackTrace();
}
但是编译器显示错误未处理的异常类型FileNotFoundException
我的观点是编译器不明白我正在通过 CustomException 捕获 FileNotFoundException 吗?
请帮忙。
最佳答案
FileNotFoundException
是 IOException
的子类,而 IOException
是 Exception 的子类。
分层 -
java.lang.Throwable
java.lang.Exception
java.io.IOException
java.io.FileNotFoundException
并且 CustomException
是 Exception
的子类,其层次结构是 -
java.lang.Throwable
java.lang.Exception
java.io.CustomException
很明显,CustomException
不在异常链中,它既不是IOException
也不是FileNotFoundException
的父类(super class),这就是为什么你可以不使用 CustomException
捕获 FileNotFoundException
。
但是您可以使用 IOException
、Exception
和 Throwable
捕获 FileNotFoundException
,但 FileNotFoundException
除外>.
关于java - 自定义异常问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14723168/