我创建了一个自定义异常类,如下所示
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?
请帮忙。
答案 0 :(得分:7)
FileNotFoundException
是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
不在Exception链中,并且它不是IOException
和FileNotFoundException
的超类,这就是为什么你不能用FileNotFoundException
抓住CustomException
{1}}。
但除FileNotFoundException
外,您可以IOException
,Exception
和Throwable
抓住FileNotFoundException
。
答案 1 :(得分:2)
编译器理解的是FileNotFoundException
和CustomException
是两个不同的例外。您需要捕获两个例外:
File file = new File("some_file_path");
try {
FileOutputStream outputStream = new FileOutputStream(file);
// do some operation
// if some cond is not satisfied
// throw new CustomException("Error Message");
} catch (CustomException | FileNotFoundException e) { // syntax valid if you are using java 7, otherwise write one more catch block
e.printStackTrace();
}
答案 2 :(得分:1)
CustomException
与FileNotFoundException
的类型不同,所以这是不合适的。
基本上你可以输入:
} catch (T e) {
}
其中T
必须是可从类型FileNotFoundException
的值分配的类型,即相同或更通用(超类)类型。
答案 3 :(得分:0)
这是FileOutputStream
的签名,File
作为参数:
public FileOutputStream(File file) throws FileNotFoundException
FileNotFoundException
是checked exception,意味着必须明确处理(捕获/抛出)。您正在捕捉CustomException
而不是必须捕获/抛出的内容(在本例中为FileNotFoundException
)。此外,FileOutputStream
属于IOException
子类,而CustomException
属于Exception
子类。在层次结构级别CustomException
和IOException
之间没有关系。
答案 4 :(得分:0)
为什么您希望您的CustomException类捕获FileNotFoundException? FileNotFoundException Class is extended by IOEXception class (IOException is extended by Exception Class)
,您的CustomException类是仅扩展Exception类,它是FileNotFoundException和Exception类的超类。