0

Why does this code throw an IOException?

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

public class Main {

    public static void main(String[] args) {
        try (Scanner scan1 = new Scanner(new File("File1.txt"));
             Scanner scan2 = new Scanner(new File("File2.txt"))) {

        } catch (IOException e) {
            System.out.println("An IOException has been thrown.");
        } 
        System.out.println("Done!");
    }
}

I am learning this from a book, but don't understand why it throws an exception. Any help is appreciated!

1
  • 1
    In your exception println, output 'e' as well so that you can see what the error is. It will tell you why it threw an exception.
    – Bek
    May 7, 2016 at 21:02

1 Answer 1

2

Because the constructor Scanner(File) throws a FileNotFoundException which is a sub class of IOException. Check the javadoc for more details.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.