为什么 FileWriter 和 FileOutputStream 有不同的异常?
Java 7 的文档 FileWriter 和 FileOutputStream显示FileWriter的构造函数抛出IOException,而FileOutputStream的构造函数抛出FileNotFoundException。
不过,这两个例外的原因是相同的。它说,“如果文件存在但是一个目录而不是常规文件,不存在但无法创建,或者由于任何其他原因无法打开”
如果是这种情况,那么为什么要为 FileOutputStream 和一个专门的异常FileWriter 的一般例外是由 Java 创建者决定的?
The docs of Java 7 for FileWriter and FileOutputStream shows that the constructor of FileWriter throws IOException, while the constructor of FileOutputStream throws FileNotFoundException.
The reason for both the exceptions is same though. It says,"if the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason"
If this is the case, then why a specialized exception for FileOutputStream and a general exception for FileWriter is decided by Java creators??
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
FileWriter
扩展了OutputStreamWriter
,其构造函数抛出UnsupportedEncodingException
。FileWriter
的实现,您会发现它使用FileOutputStream
抛出FileNotFoundException
。由于
FileWriter
构造函数现在可以抛出这两个异常中的任何一个,因此它被声明为抛出IOException
,这是这两个异常的公共超类。 (或者,也可以声明它抛出两个单独的异常。)FileWriter
extendsOutputStreamWriter
whose constructor throwsUnsupportedEncodingException
.FileWriter
, it usesFileOutputStream
which throwsFileNotFoundException
.Because the
FileWriter
constructor can now throw either of these exceptions, it is declared to throwIOException
, which is a common superclass for both exceptions. (Alternatively, it could have been declared to throw two individual exceptions.)