关闭读者和作者的异常处理

时间:2014-05-07 02:51:35

标签: java exception try-catch

我只是回顾一下我们在一个java类中编写的代码。我注意到在finally块中有一个try / catch用于关闭阅读器,但不是作者。我将复制下面的代码。任何人都可以解释为什么会这样吗?我想更好地理解。

public class UsingFiles {
public static void main(String[] args) {
    // open the input stream (from the file of this program)
    BufferedReader reader = null;
    PrintWriter writer = null;
    try {
        reader = new BufferedReader(new FileReader("./src/UsingFiles.java"));
        writer = new PrintWriter("reverseFile.txt");
        // String line;
        // while ((line = reader.readLine()) != null) {
        // System.out.println(line);
        // }
        // print the file in reverse order
        // use recursion
        reverseFile(reader, writer);
    } catch (FileNotFoundException e) {
        System.out.println("Couldn't open the file!");
    } catch (IOException e) {
        System.out.println("Problem reading the file");
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                System.out.println("Couldn't close the reader");
            }
        }
        if (writer != null) {
            writer.close();
        }
    }
}

private static void reverseFile(BufferedReader reader, PrintWriter writer)
        throws IOException {
    String line = reader.readLine();
    if (line != null) {
        reverseFile(reader, writer);
        writer.println(line);
    }
}

5 个答案:

答案 0 :(得分:3)

我可以想到两种可能性:

  1. 这是一种疏忽
  2. close()的两次调用都可以抛出异常。如果第一个抛出异常,则会跳过第二个异常 - 除非第一个异常包含在其自己的try / catch块中。第二个不需要try / catch块,因为如果失败,则不会跳过后续代码
  3. 在"现实世界"中,我会说答案是#1。我认为#2不太可能的原因是,即使您无法关闭某些流,通常也会有一些其他代码要执行。如果catch块未捕获异常(或重新抛出不同的异常),则尤其如此,因为finally块中的新异常将替换原始异常并且您永远不会知道它发生了。

    <强>更新

    正如另一个答案所指出的那样,PrintWriter.close()实际上并没有抛出IOException,即使父接口Writer确实声明close()可以抛出IOException 1}}。所以这可能是一个更好的解释。

答案 1 :(得分:1)

我相信即使读者未能关闭,其意图也是试图关闭作者。如果关闭阅读器会抛出IOException,则永远不会执行finally块的其余部分。

答案 2 :(得分:1)

这是因为PrintWriter在close()期间从不抛出异常。请参阅API。这个

            try {
                writer.close();
            } catch(IOException e) {
                System.out.println("Couldn't close the writer");
            }

将导致编译器错误:IOException的无法访问的catch块。永远不会从try语句主体

抛出此异常

答案 3 :(得分:0)

实际上应该关闭。

http://docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html

无论何时在系统上使用资源,最好关闭可以访问它的对象。

答案 4 :(得分:0)

如果您正在使用try with resource

,则无需在finally块的try块中关闭reader
try(reader = new BufferedReader(new FileReader("./src/UsingFiles.java"))
{

}

catch(Exception e)
{
}