java – 使用Exception类或FileNotFoundException类捕获异常之间的区别
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java – 使用Exception类或FileNotFoundException类捕获异常之间的区别,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1532字,纯文字阅读大概需要3分钟。
内容图文
![java – 使用Exception类或FileNotFoundException类捕获异常之间的区别](/upload/InfoBanner/zyjiaocheng/745/ae29f952f64a4f26b280c4c21871569c.jpg)
就像我有这两个场景我们必须处理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?
内容总结
以上是互联网集市为您收集整理的java – 使用Exception类或FileNotFoundException类捕获异常之间的区别全部内容,希望文章能够帮你解决java – 使用Exception类或FileNotFoundException类捕获异常之间的区别所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。