使用FileReader会导致编译器错误“未处理的异常类型FileNotFoundException”。 [英] Using FileReader causes a compiler error "unhandled exception type FileNotFoundException"

查看:79
本文介绍了使用FileReader会导致编译器错误“未处理的异常类型FileNotFoundException”。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里阅读了一些与相同问题有关的线程,但是解决方案都无法正常工作。 :/

Ive read a few threads here that relate the same problem, but the solutions arent working. :/

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

I use Eclipse, here is my program.

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(现在在整个项目目录中都放到哪里),无论如何我得到的错误是:

The error I get, no matter what I try, or where I put myscript.abc (its peppered throughout the projects directory now) is this :


未处理的异常类型
FileNotFoundException myclass.java / myproject / src / mypackage

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

结束时会拔毛。

推荐答案


未处理的异常类型FileNotFoundException myclass.java / myproject / src / mypackage

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

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

This is a compiler error. Eclipse is telling you that your program does not compile to java byte code (so of course you can't run it). For now, you can fix it by simply declaring that your program may throw this exception. Like so:

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

FileNotFoundException 是一个已检查的异常(google this),这意味着代码必须声明JVM遇到的情况。在代码中,try-catch块或throws声明向JVM指示如何处理该异常。

FileNotFoundException is a "checked exception" (google this) which means that the code has to state what the JVM should do if it is encountered. In code, a try-catch block or a throws declaration indicate to the JVM how to handle the exception.

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

For future reference, please note that the red squiggly underline in Eclipse means there is a compiler error. If you hover the mouse over the problem, Eclipse will usually suggest some very good solutions. In this case, one suggestion would be to "add a throws clause to main".

这篇关于使用FileReader会导致编译器错误“未处理的异常类型FileNotFoundException”。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆