【问题标题】:In java why does FileWriter throw IOException while FileOutputStream throw FileNotFoundException for the exact same reasons在 java 中,为什么 FileWriter 抛出 IOException 而 FileOutputStream 抛出 FileNotFoundException 的原因完全相同
【发布时间】:2015-11-06 14:37:40
【问题描述】:

来自java docs

public FileWriter(String fileName) 抛出 IOException

投掷:

IOException - 如果指定文件存在但为目录而非常规文件、不存在但无法创建或因任何其他原因无法打开

here

public FileOutputStream(File file, boolean append) throws FileNotFoundException

投掷:

FileNotFoundException - 如果文件存在但为目录而非常规文件、不存在但无法创建或因任何其他原因无法打开

这种选择有什么具体原因吗?

【问题讨论】:

  • FileOutputStream 只能在找不到文件时失败。当找不到文件或其他原因时,FileWriter 可能会失败。

标签: java filenotfoundexception ioexception filewriter fileoutputstream


【解决方案1】:

有趣的问题。

我刚刚查看了每个构造函数的代码,这有助于澄清事情:

FileWriter 使用FileOutputStreamFileOutputStream 抛出一个 FileNotFoundException,它扩展了 IOException

FileWriter extends OutputStreamWriter 的构造函数抛出 UnsupportedEncodingException,它也扩展了 IOException

FileWriter 因此,可以抛出任一异常。但由于它们都扩展了IOException,因此它在其构造函数的签名中声明了IOException

【讨论】:

    猜你喜欢
    • 2013-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-05
    • 1970-01-01
    • 2012-01-13
    • 2012-09-21
    • 1970-01-01
    相关资源
    最近更新 更多