开发者

Method may fail to close stream on exception

I get a critical error with findbugs:

The method creates an IO stream object, does not assign it to any fields, pass it to other methods, or return it, and does not appear to close it on all possible exception paths out of the method. This may result in a file descriptor leak. It is generally a good idea to use a finally block to ensure that streams are closed.

try {
...
stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
...
} catch (IOException e) {
    throw new RuntimeException(e);
} finally {
    try {
        if (stdError != null) {
            stdError.close();
        }开发者_开发问答
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

Do I need to close InputStreamReader also or p.getErrorStream (it returns InputStream)?


What happens when an exception is thrown while creating the BufferedReader object? The stream managed by the InputStreamReader object is not closed until some time in the future when the garbage collector decides to destroy the object.

You will likely have similar problems if an exception is thrown while creating the InputStreamReader object.


BufferedReader and InputStreamReader both close the underlying stream when they are closed. You should be fine by closing stdError

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜