繁体   English   中英

为什么我需要在BufferedReader中捕获close()异常但不在PrintWriter中捕获?

[英]Why do I need to catch a close() exception in BufferedReader but not in PrintWriter?

我有一个简单的文件读写功能。

private void WriteToFile(String filename, String val) {
    PrintWriter outStream = null;
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(filename);
        outStream = new PrintWriter(new OutputStreamWriter(fos));
        outStream.print(val);
        outStream.close();
    } catch (Exception e) {
        if (outStream != null) {
            outStream.close();
        }
    }
}

private String ReadFile(String filename) {
    String output = "";
    FileReader fr = null;
    BufferedReader br = null;
    try {
        fr = new FileReader(filename);
        br = new BufferedReader(fr);
        output = br.readLine();
        br.close();
    } catch (Exception e) {
        if (br != null) {
            br.close();
        }
    }

    return output;
}

建设时我得到:

unreported exception java.io.IOException; must be caught or declared to be thrown
            br.close();
                    ^

为什么我需要捕获br.close但它不抱怨WriteToFile的close()?

取自java.io.PrintWriter的源代码:

public void close() {
    try {
        synchronized (lock) {
            if (out == null)
                return;
            out.close();
            out = null;
        }
    }
    catch (IOException x) {
        trouble = true;
    }
}

IOException在PrintWriter的close()方法中被占用

从java.io.BufferedReader的源代码:

public void close() throws IOException {
    synchronized (lock) {
        if (in == null)
            return;
        in.close();
        in = null;
        cb = null;
    }
}

BufferedReader抛出IOException。

这应该回答你的问题。

为什么我需要捕获br.close但它不抱怨WriteToFile的close()?

您可以检查Java Docs。 BufferedReaderclose()方法:

public void close()
           throws IOException

PrintWriterclose()方法:

public void close()

答案是你的问题,为什么JVM不抱怨。 因为方法签名很清楚;

PrinterWriter.close()不会抛出任何异常。 如果你调用fos.close() ,它会要求你捕获/抛出异常。

在PrintWriter.java中。 捕获和处理异常。 所以你在使用时不需要抓住它。

Java来源:

 public void close() {
        try {
            synchronized (lock) {
                if (out == null)
                    return;
                out.close();
                out = null;
            }
        }
        catch (IOException x) {
            trouble = true;
        }
    }

但是在BufferedReader中抛出了异常。 所以你在使用时必须抓住它。

Java来源:

  public void close() throws IOException {
            synchronized (lock) {
                if (in == null)
                    return;
                in.close();
                in = null;
                cb = null;
            }
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM