Java异常IOException永远不会在相应的try语句的主体中抛出?

时间:2015-03-25 22:57:02

标签: java error-handling compiler-errors ioexception

通常这可能是我在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而下面的代码呢?

1 个答案:

答案 0 :(得分:2)

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

  

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

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

在您的第二个代码中,您可以添加readLine()的来电,可能来自BufferedReader,这会引发IOException