【问题标题】:Java Closing an IOStream in finally giving error: Unhandled Exception: java.io.IOExceptionJava关闭IOStream最终给出错误:未处理的异常:java.io.IOException
【发布时间】:2014-11-27 15:20:38
【问题描述】:

来自 C#,我通常会在与流交互时使用这种模式(请注意,我在这里使用的是 Java 类,但我指的是 C# 中的一种模式):

HttpURLConnection ServiceConnection;
DataOutputStream ConnectionStream;

try {
    ServiceConnection = (HttpURLConnection) ServiceUrl.openConnection();
    ConnectionStream = new DataOutputStream(ServiceConnection.getOutputStream());

    //...
}
finally {
    ConnectionStream.close();
    ServiceConnection.Disconnect();
}

据我了解,对于像 IOException 这样的已检查异常,我需要包含一个 catch 块。很公平。所以我改变了我的代码如下:

HttpURLConnection ServiceConnection;
DataOutputStream ConnectionStream;

try {
    ServiceConnection = (HttpURLConnection) ServiceUrl.openConnection();
    ConnectionStream = new DataOutputStream(ServiceConnection.getOutputStream());

    //...
}
catch (MalformedURLException e1) {
    //...
}
catch (IOException e) {
    //...
}
finally {
    ConnectionStream.close();
    ServiceConnection.Disconnect();
}

但是,这段代码给了我以下错误:Unhandled Exception: java.io.IOException on the line that I tried to close the stream in finally 块。

我在这里不明白什么?我认为 finally 块是你应该放置清理代码的地方,我认为在这里关闭流是完美的选择?

【问题讨论】:

  • finally 中的代码块与其他代码块一样;另外,如果您使用 Java 7+,请考虑使用 try-with-resources 语句
  • DataOutputStream.close 可以抛出 IOexception 所以你必须用 try catch 块包围它。此外,您没有检查ConnectionStream 是否为空。你最终可能会得到一个NullPointerException

标签: java exception-handling


【解决方案1】:

您可以使用 apache 的 IOUtils 库。它有一个方法叫做 close quiet.

finally {
        IOUtils.closeQuietly(connectionStream);
    }

否则你将不得不用 try/catch 包围 close 方法

finally {
        if (connectionStream != null) {
            try {
                connectionStream.close();
            } catch (Exception ignore) {
                // Nothing to do
            }
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-04
    • 1970-01-01
    • 2018-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多