【发布时间】:2019-04-30 09:47:59
【问题描述】:
我在 IntelliJ 中创建了一个新项目,并使用以下代码创建了一个新类:
import java.io.PrintWriter;
public class myWriter {
public static void main(String[] arg){
PrintWriter writeMe = new PrintWriter("newFIle.txt");
writeMe.println("Just writing some text to print to your file ");
writeMe.close();
}
}
我希望这会在工作目录中创建一个 txtfile,其中包含“只需编写一些文本以打印到您的文件”。但是,它只是返回了错误:
Error:(5, 31) java: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown
【问题讨论】:
-
必须捕获列出的异常类型(添加
try/catch块)或声明抛出(添加throws FileNotFoundException到您的方法声明)。 -
一遍又一遍地阅读错误,直到你知道它的含义......我的意思是来吧......
-
我对 java 很陌生,我知道如何尝试/捕获,但什么是“抛出 FileNotFoundException”,如果我希望代码正常工作,为什么我需要捕获异常?
-
FileNotFoundException是一个检查异常。这意味着编译器会检查您的代码,以确保您将在任何可能发生的情况下处理异常(或至少声明它可能发生)。
标签: java ubuntu intellij-idea