gpt4 book ai didi

java - 同时捕获java异常FileNotFound和IOException

转载 作者:搜寻专家 更新时间:2023-10-30 21:41:23 28 4
gpt4 key购买 nike

FileNotFoundException 是否是 IOException 的“子异常”?

这是我的代码,用于打开给定路径中文件的输入流:

   method(){
FileInputStream fs;
try {
fs = new FileInputStream(path);
//
fs.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

为什么我可以忽略 FileNotFound 而只捕获 IOException?FNFException 是 IOException 的一部分吗?

如果我不捕获异常,而是在我的方法中抛出 IOException 怎么办?

    method() throws IOException{

FileInputStream fs;
fs = new FileInputStream(path);
//
fs.close();

}

我可以继续在这样的调用方法中捕获 FileNotFoundException 吗?

    try {

method();

}catch (FileNotFoundException e1) {}

感谢您提供的任何帮助!

最佳答案

Is the FileNotFoundException somehow a "sub-exception" of the IOException?

是的,FileNotFoundException 扩展 IOException:

java.lang.Object
java.lang.Throwable
java.lang.Exception
java.io.IOException
java.io.FileNotFoundException

How come I can neglect the FileNotFound and just catch the IOException instead?

捕获抛出异常的基类将捕获异常,除非有更具体的 catch 子句可用。

Can I proceed to catch a FileNotFoundException at the invoking method like this?

当然!事实上,这是一件好事:您的代码应该只处理它知道如何处理的异常,并让所有其他异常传播到可以以更好的方式处理的地方。

关于java - 同时捕获java异常FileNotFound和IOException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22196066/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com