2015-10-18 72 views
1
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) { 

    } 
} 

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

这里的错误:

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

+0

在哪一行发生? –

+0

实际上,当我在其他地方调用方法时,实际发生这种情况,但这是有问题的代码 – Carl5444

回答

1

你在这里比较难以检查异常。最主要的是,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那里打扰*。

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

1

声明该构造函数抛出一个检查异常:

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. 
    } 
} 

,或者,如果没有在​​抛出一个未捕获FileNotFoundException(就像在你的代码,其中FileNotFoundException被捕获并吞下),该throws FileNotFoundException从​​删除,例如允许

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