Java 使用 JFileChooser 时出现未报告的异常

Java Unreported Exception while using JFileChooser

public FileReader() throws FileNotFoundException {
    //create fileChooser
    JFileChooser chooser = new JFileChooser();
    //open fileChooser
    int returnValue = chooser.showOpenDialog(new JFrame());
    try {
        if (returnValue == JFileChooser.APPROVE_OPTION) {
            file = chooser.getSelectedFile();
        }
    } catch (FileNotFoundException e) {

    }
}

我正在编写一个程序来读取文本文件并将其放入字符串(单词)数组中。这只是程序的文件 reader,当我尝试从代码的另一部分调用该方法时,它给我一个错误。任何想法将不胜感激;它可能是一个简单的修复,但我似乎找不到它。

这是错误:

unreported exception FileNotFoundException; must be caught or declared to be thrown

您已将构造函数声明为抛出已检查异常:

public FileReader() throws FileNotFoundException

无论在何处调用此构造函数,都必须声明它是从该方法中抛出的,例如

public static void main(String[] args) throws FileNotFoundException {
  new FileReader();
}

或者捕获并处理它,例如

public static void main(String[] args) {
  try {
    new FileReader();
  } catch (FileNotFoundException e) {
    // Handle e.
  }
}

或者,如果 FileReader() 中没有任何内容抛出未捕获的 FileNotFoundException(就像在您的代码中,FileNotFoundException 被捕获并吞下),从中删除 throws FileNotFoundException FileReader(),允许例如

public static void main(String[] args) {
  new FileReader();
}

您在这里很难被检查的异常所困扰。最主要的是 FileNotFoundException 被选中,它必须是:

  • 在使用时陷入 try...catch 语句,或者
  • 声明为通过方法签名中的 throws 声明抛出。

通常不会同时做这两件事,你现在就是这样。

作为进一步的建议,您也不想执行以下任一操作:

  • 在构造函数中抛出异常
  • 不对捕获的异常做任何事情

所以我个人的建议是捕获异常并处理它...

public FileReader()  {
    //create fileChooser
    JFileChooser chooser = new JFileChooser();
    //open fileChooser
    int returnValue = chooser.showOpenDialog(new JFrame());
    try {
        if (returnValue == JFileChooser.APPROVE_OPTION) {
            file = chooser.getSelectedFile();
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}

...但是除非我查看的是错误的库,否则 I don't see anywhere where a FileNotFoundException is even thrown on JFileChooser! 这会使您的代码足够简单 - 那时不要打扰* try...catch

*:您实际上 必须 删除它,因为捕获从未抛出的已检查异常是一个编译错误。