错误:未报告的异常FileNotFoundException;必须被抓住或宣布被抛出
问题描述:
我正在尝试创建一个将字符串输出到文本文件的简单程序。使用我在这里找到的代码,我将以下代码放在一起:
I'm trying to create a simple program that will output a string to a text file. Using code I found here, I have put together the following code:
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-grip引发了以下错误:
J-grasp throws me the following error:
----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很新,我不知道这意味着什么。任何人都能指出我正确的方向吗?
Since I'm pretty new to Java, I have no idea what this means. Can anybody point me in the right direction?
答
您没有告诉编译器有可能抛出 FileNotFoundException
a 如果文件不存在,将抛出FileNotFoundException
。
You are not telling the compiler that there is a chance to throw a FileNotFoundException
a FileNotFoundException
will be thrown if the file does not exist.
试试这个
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
}
}