0

Edit: Some of the comments below have fixed my problem. I needed to add a try catch block to my code or to add a throws Exception to my main method. This fixed the problem.

I know this question has been asked before but I tried all the recommendations and nothing has helped. I'm trying to read from a file and I keep getting the FileNotFoundException. Here is my code:

import java.io.File;
import java.io.FileReader;

public class TextParser {


    public static void main(String[] args) {
        File f = new File("C:\\Users\\jonny\\Desktop\\readme.txt");
        System.out.println(f.getAbsolutePath());
        System.out.println(f.exists());
//        FileReader file = new FileReader(f);
    }
}

With the last line commented out, the code runs and I get the output: C:\Users\jonny\Desktop\readme.txt

true

However, when I uncomment the last line, I will get this:

Error:(11, 27) java: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown

How can I fix this, I've clearly specified the absolute path. Also, the file is not open on my computer as I run this program.

Jonathan
  • 247
  • 3
  • 11
  • You need to add a `try { ... } catch(IOException ex) { ... }` block around that line or add a `throws IOException` clause to your main method. – BretC Feb 22 '19 at 15:36
  • That message means you have to either write code to catch that exception when the code is run (the file might not exist by then or might not be accessible) or throw it (e.g. via `main (...) throws Exception`). - "I've clearly specified the absolute path" - the compiler does neither know the file exists or will exist nor does it care. It _could_ happen that the file doesn't exist, hence the exception that _could_ be thrown ("exception" normally means something unexpected happened). – Thomas Feb 22 '19 at 15:37
  • I just added that line throws Exception and I am no longer getting an error. Thank you so much! – Jonathan Feb 22 '19 at 15:39
  • 1
    I think you are misunderstanding the error. The error does not say your file doesn't exists. It tells you that you should surround your FileReader with a Try-catch block – vincrichaud Feb 22 '19 at 15:39

0 Answers0