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

Java exception IOException is never thrown in body of corresponding try statement?

通常这是一个简单的问题,我可以在 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 有什么原因吗?

您的 outfile2PrintWriter。有点意外,PrintWriter methods don't throw exceptions.

Methods in this class never throw I/O exceptions, although some of its constructors may. The client may inquire as to whether any errors have occurred by invoking checkError().

这就解释了为什么您的第一个代码没有抛出 IOException

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