Introduction
The java.io.FileNotFoundException is a subclass of IOException thrown when an attempt to open a file that does not exist fails.
What is an error?
An error is an undesirable event that occurs during the execution of a program. Errors can be caused by bugs in the code, or by incorrect input from the user.
There are two types of errors: compile-time errors and run-time errors. Compile-time errors are those that occur when the code is being compiled, and are usually due to syntax errors. Run-time errors are those that occur when the code is being executed, and are usually due to problems with the input data.
What is an exception?
An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program’s instructions. When an exception occurs, it is said to be “thrown”.
What is a FileNotFoundException?
A FileNotFoundException is an exception that is thrown when a file cannot be found. This can be due to the file not existing, or because it is not accessible (for example, if it is on a blocked drive or in a protected folder).
How to handle a FileNotFoundException
If you’re trying to open a file that doesn’t exist, you’ll get a FileNotFoundException. To handle this exception, you can either try to create the file or catch the exception and handle it gracefully.
Creating the file:
If you know for sure that the file should exist, you can try to create it:
File f = new File(“myfile.txt”);
try {
f.createNewFile(); //this will create the file if it doesn’t exist
} catch (IOException e) {
//otherwise, we’ll just catch the IOException
}
Catching the exception:
if(!f.exists()) { //check if the file exists first
try {
Scanner sc = new Scanner(new File("myfile.txt")); //if it doesn't, we'll get a FileNotFoundException
//read and process information from "myfile.txt" here
} catch (FileNotFoundException e) {
System.out.println("myfile.txt was not found"); //catch and handle the exception here
}
}
Conclusion
Due to the fact that FileNotFoundException is a checked exception, and therefore requires either a try/catch block or the declaration of the exception in the throws clause, many programmers choose to simply declare it in the throws clause and let the caller of the method deal with it. However, this is not always the best solution, as it can lead to programming errors if the caller does not deal with the exception properly. Try/catch blocks should be used whenever possible so that any errors that occur can be dealt with immediately, instead of being propagated up the call stack.