【问题标题】:Can someone please point out what's wrong here有人可以指出这里有什么问题吗
【发布时间】:2020-05-30 06:58:01
【问题描述】:

我确保有我认为需要的所有例外,但它一直给我这个错误:

异常 FileNotFoundException 已被捕获 捕获(FileNotFoundException fnfe)

public class SNIDDb
{
  private char delimiter;
  private String name;
  private BufferedReader br;

  public SNIDDb(String name, char delimiter)
  {
    this.name=name;
    this.delimiter=delimiter;
    try
    {
      FileReader fr= new FileReader(name);
      br= new BufferedReader(fr);
    }
    catch(IOException i)
    {
      System.out.println(i.getMessage());
    }
    catch(FileNotFoundException fnfe)
    {
      System.out.print(fnfe.getMessage());
    }
  }

【问题讨论】:

    标签: java file exception


    【解决方案1】:

    如果您查看FileNotFoundException 的定义,您会发现它是

    public class FileNotFoundException extends IOException {
    

    因此,通过捕获基类 IOException,您实际上已经捕获了派生异常,因此您看到了错误。

    但是,如果您进一步查看您正在调用的FileReader 构造函数,它只会抛出FileNotFoundException,因此您实际上不需要在其中捕获IOException,并且可以删除该catch 子句并修复您的错误。

    【讨论】:

      【解决方案2】:

      听起来 FileNotFoundException 扩展了 IOException。尝试颠倒两个 catch 语句,你应该会很好。

      类 FileNotFoundException java.lang.Object java.lang.Throwable java.lang.异常 java.io.IOException java.io.FileNotFoundException

      https://docs.oracle.com/javase/7/docs/api/java/io/FileNotFoundException.html

      【讨论】:

      • 说当我这样做时 catch IOException 是无法访问的
      【解决方案3】:

      由于 FileNotFoundException 扩展了 IOException,您可以根据需要选择 FileNotFoundException 或 IOException。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-07-23
        • 1970-01-01
        • 2015-07-09
        • 2020-02-21
        • 2020-10-30
        • 2012-10-26
        相关资源
        最近更新 更多