Java FileNotFoundException
Example
Try to read a file that does not exist, and catch the exception:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
try {
Scanner myReader = new Scanner(new File("missing.txt"));
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("Error: the file was not found.");
}
}
}
Definition and Usage
A FileNotFoundException happens when a program tries to open a file that does not exist, or a file that it is not allowed to open.
It is a checked exception (Java requires you to catch it, or to declare it with throws). It is a kind of IOException.
Tip: Read more about files in our Java Read Files Tutorial.
Related Pages
Java Exceptions (try...catch) Tutorial
❮ Errors & Exceptions