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