为什么 Eclipse 会为以下代码发出奇怪的“资源泄漏:zin 永远不会关闭”警告,即使我使用try-with-resources
:
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:如果我for
从块中删除循环try
,警告就会消失:
// 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:如果我创建InputStream
外部try-with-resources
,也没有警告:
// 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) 的结果相同。