javafiletry-catchfilereaderfilenotfoundexception

Why did placing my file in a try catch with a FileNotFoundException work when reading a file?


I got my code to work for an assignment but it doesn't help me if I don't know why it happened so I am here to try and understand by asking the community.

I am trying to read a simple text file with 3 lines, each with one sentence of lorem ipsum. Nothing crazy. The name of the file is myFile.txt and my java class is in the exact same folder. The paths lead to the same folder both files are in. Java kept telling me that it could not find my file even though the file is in the exact folder.

Originally, I had this.

    public void readFile()  {
        File file = new File("C:\\Users\\jovan\\Documents\\ACC\\java\\Java2-Kumi\\Program4 Files\\myFile.txt");
        Scanner myReader = new Scanner(file);

        while (myReader.hasNextLine()) {
            System.out.println(myReader.nextLine());
        }
    }

Then VScode Code suggested that I do this instead as a Quick Fix

    public void readFile()  {
        File file = new File("C:\\Users\\jovan\\Documents\\ACC\\java\\Java2-Kumi\\Program4 Files\\myFile.txt");
        try (Scanner myReader = new Scanner(file)) {
            while (myReader.hasNextLine()) {
                System.out.println(myReader.nextLine());
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

After the quick fix it read the file exactly as is.

Can someone please explain why the code worked after placing it in a try/catch?


Solution

  • Java can be pretty strict about catching exceptions. The compiler knows that new Scanner(File source) can throw a FileNotFoundException, so it will only let you compile the code if you take that into consideration.

    If it did let you compile, you could get some pretty nasty knock-on effects. Someone else might try to use your method and get an error without even realizing that was something they had to worry about, which could cause a lot of frustration or confusion.

    Java gives you a few options for taking care of this:

    1. Catching, or handling the case where the exception is thrown. This is what you did. The try/catch block tells the compiler that you know the exception is possible and you will deal with it if it does. If you're going to catch an exception, you should probably do something about it besides just printing it out to prevent unexpected behavior down the line.
    2. Declaring, or telling the compiler that the method might throw the exception. This passes the exception off onto whoever is calling it. This can be useful because it lets users tailor exception handling towards their use cases. If you want to do this, take out the try/catch block and add a throws statement instead:
    public void readFile() throws FileNotFoundException {
        File file = new File("C:\\Users\\jovan\\Documents\\ACC\\java\\Java2-Kumi\\Program4 Files\\myFile.txt");
        Scanner myReader = new Scanner(file);
        while (myReader.hasNextLine()) {
            System.out.println(myReader.nextLine());
        }
    }
    

    The throws keyword tells the compiler that your method could potentially throw a given exception, which will make the compiler force others to be careful with your method just like it forced you to be careful with this one.

    This isn't true of all exceptions. As @Rifat noted, it only applies to checked exceptions; unchecked exceptions don't need to be handled so explicitly.