【发布时间】: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)不会抛出IOException而stdin.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