微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java – 使用Exception类或FileNotFoundException类捕获异常之间的区别

就像我有这两个场景我们必须处理FileNotFoundException

情况1:

try {
        FileInputStream fis = new FileInputStream("test1.txt");
    } catch (FileNotFoundException e) {
        e.printstacktrace();
    }

案例2:

try {
        FileInputStream fis = new FileInputStream("test1.txt");
    } catch (Exception e) {
        e.printstacktrace();
    }

在两种情况下,打印的Stack Trace都是相同的.我想知道两种实现之间的区别以及应该首选的内容

解决方法

docs开始,它给出了原因:

“A subclass inherits all the members (fields,methods,and nested
classes) from its superclass. Constructors are not members,so they
are not inherited by subclasses,but the constructor of the superclass
can be invoked from the subclass.”

Exception类是所有其他异常类的父级.因此,如果您知道要获取FileNotFoundException,那么最好使用该异常.制作例外是一个通用的电话.

这有助于您理解:

因此,您可以看到Exception类处于更高层次结构,因此它意味着它将捕获除FileIOExcetion之外的任何异常.但是,如果要确保尝试打开由指定路径名表示的文件失败,则必须使用FileIOExcetion.

所以这是一个理想的方法应该是:

try {
      // Lets say you want to open a file from its file name.
    } catch (FileNotFoundException e) {
      // here you can indicate that the user specified a file which doesn't exist.
      // May be you can try to reopen file selection dialog Box.
    } catch (IOException e) {
      // Here you can indicate that the file cannot be opened.
    }

而相应的:

try {
  // Lets say you want to open a file from its file name.
} catch (Exception e) {
  // indicate that something was wrong
  // display the exception's "reason" string.
}

另请查看:Is it really that bad to catch a general exception?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐