【发布时间】: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