Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
343 views
in Technique[技术] by (71.8m points)

java - Using FileReader causes a compiler error "unhandled exception type FileNotFoundException"

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

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("
AbsPath : " + new File(".").getAbsolutePath());
    System.out.println("
user.dir : " + System.getProperty("user.dir"));


}

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

}

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

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

Wits end, pulling hairs.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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 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.

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".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...