Lucas Dryer Lucas Dryer - 3 months ago 20
Java Question

Why does this code throw an IOException?

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!

Answer

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