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.
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
, andRandomAccessFile
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.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With