Java资源管理:了解Findbugs的结果 [英] Java resource management: understanding Findbugs results

查看:176
本文介绍了Java资源管理:了解Findbugs的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Findbugs告诉我一个打开两个 Closeable 实例的方法,但我不明白为什么。

Findbugs bugs me about a method which opens two Closeable instances, but I can't understand why.

public static void sourceXmlToBeautifiedXml(File input, File output)
        throws TransformerException, IOException, JAXBException {

    FileReader fileReader = new FileReader(input);
    FileWriter fileWriter = new FileWriter(output);

    try {
        // may throw something
        sourceXmlToBeautifiedXml(fileReader, fileWriter);
    } finally {
        try {
            fileReader.close();
        } finally {
            fileWriter.close();
        }
    }
}



Findbugs分析



Findbugs告诉我

Findbugs analysis

Findbugs tells me

Method [...] may fail to clean up java.io.Reader [...]

并指向行FileReader fileReader = ...

谁错了:我或Findbugs?

Who is wrong: me or Findbugs?

推荐答案

FindBugs是正确的:如果FileWriter的构造函数抛出异常,文件阅读器将不会被关闭。要验证这一点,请尝试为输出传递无效的文件名。

FindBugs is correct: If the FileWriter's constructor throws an exception, the file reader will not be closed. To verify this, try passing an invalid filename for output.

我会按如下方式进行:

    FileReader fileReader = new FileReader(input);

    try {
        FileWriter fileWriter = new FileWriter(output);
        try {
            // may throw something
            sourceXmlToBeautifiedXml(fileReader, fileWriter);
        } finally {
            fileWriter.close();
        }
    } finally {
        fileReader.close();
    }

请注意,关闭时抛出的异常处理可以改进,因为留下了通过抛出异常终止块将导致try-statement通过抛出该异常来终止,吞下try-block中抛出的任何异常,这通常对调试更有用。请参阅duffymo的回答,了解如何避免这种情况。

Note that the handling of exception thrown when closing could be improved, since leaving a finally-block by throwing an exception will cause the try-statement to terminate by throwing that exception, swallowing any exception thrown in the try-block, which generally would be more useful for debugging. See duffymo's answer for a simple way on how to avoid this.

编辑:从Java 7开始,我们可以使用try-with-resources声明,允许对这些极端情况进行正确和粗略的处理:

Edit: Since Java 7, we can use the try-with-resources statement, which permits correct and concicse handling of these corner cases:

try (
    FileReader fileReader = new FileReader(input); 
    FileWriter fileWriter = new FileWriter(output)
) {
    // may throw something
    sourceXmlToBeautifiedXml(fileReader, fileWriter);
}

这篇关于Java资源管理:了解Findbugs的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆