Java FileNotFoundException

Java provides FileNotFoundException exception in order to express that the specified file can not be found or accessed. This exception is very common for file and folder-related operations. In this tutorial, we will examine the FileNotFoundException class, causes, how to throw and catch, and also logging FileNotFoundException.

FileNotFoundException Class

The FileNotFoundException is created from the java.lang.Object -> java.lang.Throwable -> java.lang.Exception -> java.lang.IOException -> java.io.FileNotFound . As we can see that the FileNotFoundException is a class from the java.io namespace. As we can see that the FileNotFoundException extends the IOException .

FileNotFoundException Class

FileNotFoundException Causes

The FileNotFoundException can be occure or thrown for different reasons. Generally the FileInputStream , FileOutputStream and RandomAccessFile classes and related classes throws if the specified file can not be found or accessed.

  • The specified path is not exist during execution of the Java code.
  • The specified path is not correct where some mistyping exist.
  • The read only file is tried to be open as writeable mode.
  • The permissions are not set correctly and the executable do not have required permissions to access specified file.

Catch/Handle FileNotFoundException

The FileNotFoundException can be handled or catched by using the try...catch mechnism. In the following Java code snippet the FileNotFoundException is catched with the catch keyword and some properties and information about the exception is printed.

try{
   new File("/abc/def/myfile.txt").createNewFile();
}
catch(FileNotFoundException ex){

   //Print FileNotFoundException cause
   System.out.println(ex.getCause());

   //Print StackTrace
   System.out.println(ex.getStackTrace());
}

Throw FileNotFoundException

The FileNotFoundException is very useful exception where it may the thrown manually. We can also provide the message text or content as parameter to the FileNotFoundException() method. In the following example we set the exception message as “The database file not found”.

throw FileNotFoundException("The database file not found");

Leave a Comment