为什么 FileWriter 和 FileOutputStream 有不同的异常?

发布于 2024-12-28 14:52:40 字数 545 浏览 4 评论 0原文

Java 7 的文档 FileWriterFileOutputStream显示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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

霊感 2025-01-04 14:52:40
  1. FileWriter 扩展了 OutputStreamWriter,其构造函数抛出 UnsupportedEncodingException
  2. 如果您查看 FileWriter 的实现,您会发现它使用 FileOutputStream 抛出 FileNotFoundException

由于 FileWriter 构造函数现在可以抛出这两个异常中的任何一个,因此它被声明为抛出 IOException,这是这两个异常的公共超类。 (或者,也可以声明它抛出两个单独的异常。)

  1. FileWriter extends OutputStreamWriter whose constructor throws UnsupportedEncodingException.
  2. If you look at the implementation of FileWriter, it uses FileOutputStream which throws FileNotFoundException.

Because the FileWriter constructor can now throw either of these exceptions, it is declared to throw IOException, which is a common superclass for both exceptions. (Alternatively, it could have been declared to throw two individual exceptions.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文