错误:未报告的异常FileNotFoundException;必须捕获或声明抛出

15

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

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还比较陌生,不知道这是什么意思。有人能指点一下吗?


1
在互联网上搜索“java异常教程”,并学习其中一个教程。 - Klas Lindbäck
1
对于初学者和简单的一次性程序,可以像黑豹建议的那样,在main头行中添加throws FileNotFoundException(或更通用的throws IOException)。随着您变得更加复杂,您将希望使用try/catch处理程序,但是一步一步来。 - Hot Licks
虽然你可能需要再多搜索一些,但是你的问题表述得很好,给你点赞。 - Hot Licks
4个回答

15

你没有告诉编译器有可能会抛出一个 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
    }
}

谢谢!成功让它运行起来了 :) - user2956248

3

如果您是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();
    }
}

2

PrintWriter 可能会因为文件出现问题,例如文件不存在而抛出异常。因此,您需要添加

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

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


-1
这意味着当您调用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);
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接