【问题标题】:Strange "Resource leak: stream is never closed" with try-with-resources if Exception is thrown in a loop如果在循环中抛出异常,则使用 try-with-resources 奇怪的“资源泄漏:流永远不会关闭”
【发布时间】:2014-06-11 06:08:49
【问题描述】:

为什么即使我使用try-with-resources,Eclipse 也会对以下代码发出奇怪的“资源泄漏:zin 从未关闭”警告:

Path file = Paths.get("file.zip");
// Resource leak warning!
try (ZipInputStream zin = new ZipInputStream(Files.newInputStream(file))) {
    for (int i = 0; i < 5; i++)
        if (Math.random() < 0.5)
            throw new Exception();
} catch (Exception e) {
    e.printStackTrace();
}

如果我在代码上修改“任何内容”,警告就会消失。下面我列出了 3 个修改后的版本,它们都可以(没有警告)。


Mod #1:如果我从 try 块中删除 for 循环,警告就会消失:

// This is OK (no warning)
try (ZipInputStream zin = new ZipInputStream(Files.newInputStream(file))) {
    if (Math.random() < 0.5)
        throw new Exception();
} catch (Exception e) {
    e.printStackTrace();
}

Mod #2:如果我保留 for 循环但我删除了包装 ZipInputStream,也不会发出警告:

// This is OK (no warning)
try (InputStream in = Files.newInputStream(file))) {
    for (int i = 0; i < 5; i++)
        if (Math.random() < 0.5)
            throw new Exception();
} catch (Exception e) {
    e.printStackTrace();
}

Mod #3:如果我在try-with-resources 之外创建InputStream,也不会出现警告:

// This is also OK (no warning)
InputStream in = Files.newInputStream(file); // I declare to throw IOException
try (ZipInputStream zin = new ZipInputStream(in)) {
    for (int i = 0; i < 5; i++)
        if (Math.random() < 0.5)
            throw new Exception();
} catch (Exception e) {
    e.printStackTrace();
}

我使用 Eclipse Kepler (4.3.1),但也使用 Kepler SR2 (4.3.2) 获得相同的结果。

【问题讨论】:

    标签: java eclipse warnings compiler-warnings try-with-resources


    【解决方案1】:

    这似乎是 Eclipse 中的一个已知错误:[compiler][resource] Bad resource leak problem on return inside while loop (resource passed on in finally block

    我自己也对此有所了解,并在跟踪器上添加了我的投票。

    更新:上述错误已在 4.5 M7 中得到解决。这将包含在 Eclipse 4.5(“Mars”)的最终版本中 - 预计将于 2015 年 6 月 24 日发布。

    【讨论】:

    • 我假设是这样的,但很高兴确认我不必改变我的逻辑或风格,这只是 IDE 中的一个错误。
    猜你喜欢
    • 1970-01-01
    • 2020-07-30
    • 2012-09-13
    • 1970-01-01
    • 1970-01-01
    • 2011-10-16
    • 2020-01-01
    • 1970-01-01
    • 2012-12-20
    相关资源
    最近更新 更多