簡體   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