FileNotFoundException vs. NoSuchFileException

喜夏-厌秋 提交于 2019-12-21 07:27:30

问题


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.


回答1:


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.




回答2:


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.




回答3:


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




回答4:


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.



来源:https://stackoverflow.com/questions/27424237/filenotfoundexception-vs-nosuchfileexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!