【问题标题】:Getting FileNotFoundException even though I declared it to be thrown即使我声明它被抛出,也得到 FileNotFoundException
【发布时间】:2013-07-07 04:44:23
【问题描述】:

我目前正在使用链表编写文本编辑器,我已经完成了很多工作,但是在尝试测试程序的命令行时遇到了 FileNotFoundException,即使我声明它会被抛出。

这是我的编辑器的骨架:

public class Editor  {

  public Editor() { 

  }

  public void commandLine() throws FileNotFoundException {

  }
}

这是我的程序的驱动程序:

public class EditorTest
{
  public static void main(String[] args) 
  {
        Editor asdf = new Editor(); 
        asdf.commandLine();

    }
}

即使我声明它是在我的命令行方法中抛出的,我仍然收到未报告的 FileNotFoundException 的错误。怎么了?

【问题讨论】:

  • throw它到main,但你不在那里catch/throw它。这甚至是如何编译的?

标签: java exception throws


【解决方案1】:

您需要将throws FileNotFoundException 添加到您的main 方法中。或者,您可以添加:

    try {
        asdf.commandLine();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

到您的 main 方法,具体取决于您需要根据该异常执行的操作。

【讨论】:

    【解决方案2】:

    你也需要在 main 上声明它

    public static void main(String[] args) throws FileNotFoundException {
    

    【讨论】:

      【解决方案3】:

      在方法中声明要抛出的异常(即使用 throws MyException)不会阻止抛出异常,而是允许该方法为该方法的调用者抛出异常必须抓住那个异常

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-06-13
        • 1970-01-01
        • 1970-01-01
        • 2022-06-15
        • 1970-01-01
        • 2012-08-31
        • 1970-01-01
        相关资源
        最近更新 更多