【问题标题】:error: unreported exception FileNotFoundException; must be caught or declared to be thrown错误:未报告的异常 FileNotFoundException;必须被抓住或宣布被扔掉
【发布时间】:2013-11-05 12:26:28
【问题描述】:

我正在尝试创建一个将字符串输出到文本文件的简单程序。使用我在这里找到的代码,我整理了以下代码:

import java.io.*;

public class Testing {

  public static void main(String[] args) {

    File file = new File ("file.txt");
    file.getParentFile().mkdirs();

    PrintWriter printWriter = new PrintWriter(file);
    printWriter.println ("hello");
    printWriter.close();       
  }
} 

J-grasp 向我抛出以下错误:

 ----jGRASP exec: javac -g Testing.java

Testing.java:10: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
    PrintWriter printWriter = new PrintWriter(file);
                              ^
1 error

 ----jGRASP wedge2: exit code for process is 1.

由于我对 Java 还很陌生,所以我不知道这意味着什么。谁能指出我正确的方向?

【问题讨论】:

  • 在互联网上搜索 java exception tutorial 并完成您找到的教程之一。
  • 对于初学者和简单的一次性程序,将 throws FileNotFoundException(或者,更一般地说,throws IOException)添加到 main 标题行,正如 Black Panther 所建议的那样。随着您变得越来越复杂,您将希望使用 try/catch 处理程序,但一次只执行一步。
  • +1 表示一个明确的问题,但如果你再努力一点,你可能会找到答案。

标签: java printwriter


【解决方案1】:

你没有告诉编译器有机会抛出FileNotFoundException 如果文件不存在,将抛出FileNotFoundException

试试这个

public static void main(String[] args) throws FileNotFoundException {
    File file = new File ("file.txt");
    file.getParentFile().mkdirs();
    try
    {
        PrintWriter printWriter = new PrintWriter(file);
        printWriter.println ("hello");
        printWriter.close();       
    }
    catch (FileNotFoundException ex)  
    {
        // insert code to run when exception occurs
    }
}

【讨论】:

  • 谢谢!设法让它启动并运行:)
【解决方案2】:

如果您是 Java 新手,只是想学习如何使用 PrintWriter,这里有一些基本代码:

import java.io.*;

public class SimpleFile {
    public static void main (String[] args) throws IOException {
        PrintWriter writeMe = new PrintWriter("newFIle.txt");
        writeMe.println("Just writing some text to print to your file ");
        writeMe.close();
    }
}

【讨论】:

    【解决方案3】:

    如果文件有问题,PrintWriter 可能会抛出异常,例如文件不存在。所以你必须添加

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

    然后它将编译并使用try..catch 子句来捕获和处理异常。

    【讨论】:

      【解决方案4】:

      这意味着当您调用new PrintWriter(file) 时,当您要写入的文件不存在时,它可能会抛出异常。所以你要么需要处理那个异常,要么让你的代码重新抛出它以供调用者处理。

      import java.io.*;
      
      public class Testing {
      
          /**
           * This writes a string to a file.
           * If an exception occurs, we don't care if nothing gets written.
           */
          public void writeToFileWithoutThrowingExceptions(File file, String text) {
              // Yes, we could use try-with-resources here,
              // but that would muddy the example.
              PrintWriter printWriter;
              try {
                  printwriter = new PrintWriter(file);
                  printWriter.println(text);
              } catch (FileNotFoundException fnfe) {
                  // Do something with that exception to handle it.
                  // Since we said we don't care if our text does not get written,
                  // we just print the exception and move on.
                  // Printing the exception like this is usually a bad idea, since
                  // now no-one knows about it. Logging is better, but even better
                  // is figuring out what we need to do when that exception occurs.
                  System.out.println(fnfe);
              } finally {
                  // Whether an exception was thrown or not,
                  // we do need to close the printwriter.
                  printWriter.close();
              }
          }
      
          /**
           * This writes a string to a file.
           * If an exception occurs, we re-throw it and let the caller handle it.
           */
          public void writeToFileThrowingExceptions(File file, String text) throws FileNotFoundException {
              // We use try-with-resources here. This takes care of closing
              // the PrintWriter, even if an exception occurs.
              try (PrintWriter printWriter = new PrintWriter(file)) {
                  printWriter.println(text);
              }
          }
          
          public static void main(String[] args) {
              File file = new File("file.txt");
              file.getParentFile().mkdirs();
      
              // We call the method that doesn't throw an exception
              writeToFileWithoutThrowingExceptions(file, "Hello");
              
              // Then we call the method that _can_ throw an exception
              try {
                  writeToFileThrowingExceptions(file, "World");
              } catch (FileNotFoundException fnfe) {
                  // Since this method can throw an exception, we need to handle it.
                  // Note that now we have different options for handling it, since             
                  // we are now letting the caller handle it.
                  // The caller could decide to try and create another file, send
                  // an e-mail, or just log it and move on.
                  // Again, as an example, we just print the exception, but as we
                  // discussed, that is not the best way of handling one.
                  System.out.println(fnfe);
              }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多