gpt4 book ai didi

java - 使用 FileReader 会导致编译器错误 "unhandled exception type FileNotFoundException"

转载 作者:行者123 更新时间:2023-12-02 04:27:37 24 4
gpt4 key购买 nike

我在这里阅读了一些涉及相同问题的线程,但解决方案不起作用。 :/

我使用Eclipse,这是我的程序。

package mypackage;
import java.io.*;


public class myclass {


public static void main(String[] args) {
//String myfile = "/home/jason/workspace/myproject/src/mypackage/myscript.abc";
String myfile = "src/mypackage/myscript.abc";
File file1 = new File(myfile);
if(file1.exists()) {
log(myfile + " exists. length : " + myfile.length());
}
else{
log(myfile + " does not exist");
//System.exit(1);
}

//FileReader fr = new FileReader("myscript.abc");//I uncomment this and die inside


System.out.println("\nAbsPath : " + new File(".").getAbsolutePath());
System.out.println("\nuser.dir : " + System.getProperty("user.dir"));


}

public static void log(String s){
System.out.println(s);
}

}

无论我尝试什么,或者将 myscript.abc (现在遍布整个项目目录)放在哪里,我得到的错误都是这样的:

Unhandled exception type FileNotFoundException myclass.java /myproject/src/mypackage

智勇双全,拔头发。

最佳答案

Unhandled exception type FileNotFoundException myclass.java /myproject/src/mypackage

这是一个编译器错误。 Eclipse 告诉您您的程序未编译为 java 字节代码(因此您当然无法运行它)。现在,您可以通过简单地声明您的程序可能抛出此异常来修复它。就像这样:

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

FileNotFoundException 是一个“受检查的异常”(google this),这意味着代码必须声明 JVM 在遇到该异常时应该做什么。在代码中,try-catch block 或 throws 声明向 JVM 指示如何处理异常。

为了将来引用,请注意 Eclipse 中的红色波浪下划线表示存在编译器错误。如果将鼠标悬停在问题上,Eclipse 通常会建议一些非常好的解决方案。在这种情况下,一个建议是“向 main 添加一个 throws 子句”。

关于java - 使用 FileReader 会导致编译器错误 "unhandled exception type FileNotFoundException",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6488339/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com