同时捕获java异常FileNotFound和IOException [英] Catching java exceptions FileNotFound and IOException at the same time

查看:2244
本文介绍了同时捕获java异常FileNotFound和IOException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

FileNotFoundException在某种程度上是IOException的子异常吗?

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

这是我的代码在给定路径打开文件的输入流:

This is my code opening an input stream to a file at the given path:

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

为什么我可以忽略FileNotFound并抓住而是IOException?
FNFException是否是IOException的一部分?

How come I can neglect the FileNotFound and just catch the IOException instead? Is the FNFException a part of the IOException?

如果我在我的方法中抛出IOException,该怎么办?

Instead of catching the exceptions, what if I throw an IOException in my method?

    method() throws IOException{

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

    }

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

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

    try {

         method();

    }catch (FileNotFoundException e1) {}

感谢您的帮助也许能够提供!

Thanks for any help you might be able to provide!

推荐答案


FileNotFoundException是不是一个sub-exception的IOException?

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

是, FileNotFoundException extends IOException


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

为什么我可以忽略FileNotFound而只是捕获IOException?

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

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

Catching a base class of the exception being thrown will catch the exception, unless there is a more specific catch clause available.


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

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

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

Absolutely! In fact, this is a good thing to do: your code should handle only the exceptions with which it knows how to deal, and let all other exceptions propagate to a place where it could be dealt with in a better way.

这篇关于同时捕获java异常FileNotFound和IOException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆