Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FileNotFoundException vs. NoSuchFileException

I noticed another Java exception for indicating that file does not exist - NoSuchFileException. I was tasked to refactor a certain api which throws both of these from differen methods and I would like to use just one.

Should I map NoSuchFileException to file to FileNotFoundException ? Should I use NoSuchFileException instead of FileNotFoudnException because it is more specific?

EDIT: Updated the question. I read the documentation before posting this question and know the basic difference. I was hoping for additional information and the guidance in this case since exception handling by type is important for the clients of the service api and I would like to avoid the case when the check needs to be done for both exception types.

like image 576
ps-aux Avatar asked Dec 11 '14 13:12

ps-aux


4 Answers

FileNotFoundException

Signals that an attempt to open the file denoted by a specified pathname has failed. This exception will be thrown by the FileInputStream, FileOutputStream, and RandomAccessFile constructors when a file with the specified pathname does not exist. It will also be thrown by these constructors if the file does exist but for some reason is inaccessible, for example when an attempt is made to open a read-only file for writing.

NoSuchFileException

Checked exception thrown when an attempt is made to access a file that does not exist.

The documentation is self-explanatory.

like image 60
Jeroen Vannevel Avatar answered Sep 21 '22 20:09

Jeroen Vannevel


Unlike NoSuchFileException, FileNotFoundException does not necessarily mean that file doesn't exist, it might just be inaccessible. Apart from that I am not sure how thy're any different.

like image 42
Lucas Avatar answered Sep 21 '22 20:09

Lucas


IMHO, there is a nuance in the semantics of those two exceptions. NoSuchFileException is generally used when there is no File at the expected location while FileNotFoundException is used as well for this case, but also in the case the file is present but can't be accessed. (permission issue,etc ...)

Moreover, note that NoSuchFileException was introduced in Java 7, thus for your specific task, I'd stick to FileNoteFoundException as it's more general and compatible with Java 1.6

like image 41
Loïc Gammaitoni Avatar answered Sep 19 '22 20:09

Loïc Gammaitoni


NoSuchFileException extends the new (as of 1.7) FileSystemException subclass of IOException while FileNotFoundException is a direct subclass of IOException. As a new parent class, FileSystemException should be as complete as possible, hence the addition of NoSuchFileException, despite the appearance of redundancy. The NotDirectoryException and AccessDeniedException subclasses flesh out the earlier functionality nicely, rather than leaving the several possibilities in one undistinguishable clump.

like image 36
elissaf Avatar answered Sep 17 '22 20:09

elissaf