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?

相关文章

Java中的String是不可变对象 在面向对象及函数编程语言中,不...
String, StringBuffer 和 StringBuilder 可变性 String不可变...
序列化:把对象转换为字节序列的过程称为对象的序列化. 反序...
先说结论,是对象!可以继续往下看 数组是不是对象 什么是对...
为什么浮点数 float 或 double 运算的时候会有精度丢失的风险...
面试题引入 这里引申出一个经典问题,看下面代码 Integer a ...