加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-15 04:27:14 所属栏目:Java 来源:网络整理
导读:就像我有这两个场景我们必须处理FileNotFoundException 情况1: try { FileInputStream fis = new FileInputStream("test1.txt"); } catch (FileNotFoundException e) { e.printStackTrace(); } 案例2: try { FileInputStream fis = new FileInputStream("t
就像我有这两个场景我们必须处理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?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读