Java program gives me FileNotFoundException when the file I am reading from exists but then works perfectly fine if I handle the exception

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class WordJumble {

    public static void main(String[] args) throws FileNotFoundException {
        // TODO Auto-generated method stub
        File file = new File("F:/Files/Topic.txt");
        Scanner sc = new Scanner(file); 

        String title = sc.nextLine();
        System.out.println(title);
        for(int i=0;i<10;i++){
            System.out.println(sc.nextLine());
        }
    }
}

Currently the program does what I want it to, but why is it giving me an error about the file not existing? When I add the throws clause to ignore the error it is able to find the file without issue.

728x90

2 Answers Java program gives me FileNotFoundException when the file I am reading from exists but then works perfectly fine if I handle the exception

While the wording of the error may be a little confusing, the error isn't a FileNotFoundException in and of itself but is instead a complaint that you aren't dealing with the possibility of such an exception being thrown. All your compiler is telling you is that you need to deal with the possibility of the file not being where you think it is. Therefore, when you add throws FileNotFoundException to the method signature the compiler is satisfied and your error goes away.

3 months ago

When you said 'add the statement to ignore the error' you meant adding the 'throws...' clause to the definition of main so it would compile cleanly. Right?

What's going on is that Scanner many throw a FileNotFoundException if the file is not found. This exception must be handled (caught) somewhere.

Instead, you elected not to handle, and said that it could propagate out from main.

The appropriate way to do this is use a try - catch construction.

try {
   Scanner sc = new Scanner(file);
   :
   :
catch (FileNotFoundException ex) {
   ... print an error or something ...
}

This sort of approach is used so that the error handling is 'out of line' of the main flow of the code.

3 months ago