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

qui*_*tin 3 java exception

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

情况1:

    try {
        FileInputStream fis = new FileInputStream("test1.txt");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } 
Run Code Online (Sandbox Code Playgroud)

案例2:

    try {
        FileInputStream fis = new FileInputStream("test1.txt");
    } catch (Exception e) {
        e.printStackTrace();
    }
Run Code Online (Sandbox Code Playgroud)

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

Rah*_*thi 5

文档中可以看出原因:

"子类从其超类继承所有成员(字段,方法和嵌套类).构造函数不是成员,因此子类不会继承它们,但可以从子类调用超类的构造函数."

Exception类是所有其他异常类的父级.因此,如果你知道你将获得FileNotFoundException它,那么使用该异常是好的.使这Exception是一个通用的电话.

这有助于您理解:

在此输入图像描述

因此,您可以看到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.
    }
Run Code Online (Sandbox Code Playgroud)

而相应的:

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.
}
Run Code Online (Sandbox Code Playgroud)

还要检查一下:捕获一般异常真的那么糟糕吗?