【问题标题】:Java exception IOException is never thrown in body of corresponding try statement?Java异常IOException永远不会在相应的try语句的主体中抛出?
【发布时间】:2015-05-29 20:32:30
【问题描述】:

通常这是一个我可以在 StackExchange 上搜索的简单问题,但我发现的其他问题似乎与我现在所处的情况不同。

filename = stdin.readLine().trim();
FileWriter fw2 = new FileWriter (filename);
BufferedWriter bw2 = new BufferedWriter (fw2);
PrintWriter outFile2 = new PrintWriter (bw2);
try {
    outFile2.print(office1);
    System.out.print(filename+" was written\n");
}
catch (IOException e) {
    System.out.print(filename+" was not found\n");
}
finally {
    outFile2.close();
}

显然,编译器声称由于某种原因,这个 try 块没有抛出 IOException。另外,另一个需要注意的细节是 office1 是一个初始化和实例化的对象。 现在这就是棘手的地方。编译器(在我写这段代码之前)声称下一段代码非常好:

filename = stdin.readLine().trim();
FileWriter fw = new FileWriter (filename);
BufferedWriter bw = new BufferedWriter (fw);
PrintWriter outFile = new PrintWriter (bw);
try {
    String input = stdin.readLine().trim();
    System.out.print("Please enter a string to write in the file:\n");
    outFile.print (input+"\n");
    System.out.print(filename+" was written\n");
}
catch (IOException exception) {
    System.out.println (filename+ " was not found");
}
finally {
    outFile.close();
}

编译器为什么一直抱怨上层代码没有抛出 IOException 而下层代码却有什么原因?

【问题讨论】:

  • 您认为IOException 可以在您的 sn-ps 中的哪个位置输入,您为什么这么认为?
  • 也许outFile.print(String) 不会抛出IOExceptionstdin.readLine() 会?
  • @NiekHaarman outFile.print(String) 实际上不会将字符串打印到某种形式的文件中,因此应该抛出 IOException 吗?显然它不会抛出 IOException,而是以某种方式写入文件?抱歉,我只是不明白其中的一些内容,因为我的大学老师没有向我们彻底解释。
  • @SotiriosDelimanolis try 块中有两行代码,其中之一是System.out.println()。使用我不可思议的推理能力,我猜 OP 认为 PrintWriter.print() 应该抛出一个 IOException,考虑到大多数文件编写者会抛出一个 IOException,这是一个合理的事情(这个不会,但大多数会抛出)。
  • 它是否抛出IOException 主要是编写方法或类的人的设计选择。虽然大多数作家确实在出现问题时抛出IOException,但显然这个没有。如果您想查看是否出现问题,您必须自己轮询实例。另请参阅rgettman's answer

标签: java error-handling compiler-errors ioexception


【解决方案1】:

您的outfile2PrintWriter。有点令人惊讶的是,PrintWriter methods don't throw exceptions

这个类中的方法从不抛出 I/O 异常,尽管它的一些构造函数可能。客户端可以通过调用 checkError() 来查询是否发生错误。

这解释了为什么您的第一个代码不会抛出 IOException

在您的第二个代码中,您添加了对readLine() 的调用,可能来自BufferedReader,它确实抛出了IOException

【讨论】:

  • 显然我做错了事。我被告知使用 BufferedWriter 并将其插入 PrintWriter 以将序列化对象写入文件。我猜我应该在这里做不同的事情?
猜你喜欢
  • 1970-01-01
  • 2011-05-18
  • 2014-05-02
  • 1970-01-01
  • 1970-01-01
  • 2017-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多