Why is Eclipse giving a strange "Resource leak: zin is never closed" warning for the following code even though I use 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();
}
If I modify "anything" on the code, the warning goes away. Below I list 3 modified versions which are all OK (no warnings).
Mod #1: If I remove the for
loop from the try
block, the warning goes away:
// 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: Also no warning if I keep the for
loop but I remove the wrapping 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: If I create the InputStream
outside the try-with-resources
, also no warning:
// 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();
}
I use Eclipse Kepler (4.3.1) but also the same result with Kepler SR2 (4.3.2).