FileNotFoundException in Java
intermediate· Exceptions · Error Handling
Problem
FileNotFoundException is thrown when code tries to open a file for reading and the file simply isn't there — a checked exception that has to be caught or declared.
Attempt to open a file that doesn't exist and handle the resulting exception.
Input
new FileReader("missing-file.txt")
Output
Error: File not found
Java Program
Java
import java.io.FileReader;
import java.io.FileNotFoundException;
public class FileNotFoundExample {
public static void main(String[] args) {
try {
FileReader reader = new FileReader("missing-file.txt");
} catch (FileNotFoundException e) {
System.out.println("Error: File not found"); // fixed message avoids OS-specific text
}
}
}Output
Error: File not found
Core Logic
Wrapping the file-opening call in a try-catch that targets FileNotFoundException specifically catches exactly this one failure mode, by name.
How It Works
- 1
new FileReader("missing-file.txt")attempts to open a file that doesn't exist on disk. - 2Since the file can't be found, the constructor throws a
FileNotFoundExceptionbeforereaderis ever assigned. - 3
catch (FileNotFoundException e)matches that exact exception type, printing a fixed error message. - 4Because this is a checked exception, the compiler wouldn't allow this call to sit outside a try-catch (or a
throwsdeclaration) in the first place.
Since
missing-file.txt doesn't exist, the constructor throws immediately and the catch block prints "Error: File not found".💡
Key Point: Catching the specific FileNotFoundException type only handles this one failure — a different I/O failure elsewhere in the same try block, of a different exception type, would slip past this catch entirely.
Key Concepts
FileReaderchecked exceptiontry / catch