-2

In the following block:

    try (final InputStream fis = new BufferedInputStream(Files.newInputStream(f.toPath()));
            final ArchiveInputStream ais = factory.createArchiveInputStream(fn, fis)) {
        System.out.println("Created " + ais.toString());
        ArchiveEntry ae;
        while ((ae = ais.getNextEntry()) != null) {
            System.out.println(ae.getName());
        }
    }

is this equivalent to the following block:

try {
    final InputStream fis = new BufferedInputStream(Files.newInputS...;
} catch {
    System.out.println("Created " + ais.toString());...
}

I stumbled across this syntax for try/catch in an apache common's library, and I'm not really sure how to take it. If I'm not correct in the only assumption that I can think of here, can anybody help me understand it or point me to a reference that explains this syntax? I've googled and searched aplenty on here and haven't been able to find anything applicable, though admittedly my search-fu is not the best.

Thanks in advance!

1 Answers1

0

No. The first is try with resources, which isn't an intuitive name. It's used when you need to use a resource and then close it. It saves you from having to manually close those every time and effectively limits the scope of the resources to within the curly braces.

The latter one is not the same: the resource fis will still be open after the try/catch block has exited. try-with-resources was introduced to fix this issue.

  • Please explain what you mean by: "the resource fis will still exist after the try/catch block was exited". – tsolakp Feb 08 '18 at 02:36
  • Some resources like file readers etc. need to be closed after their use is finished. In the first block the resource `fis` is closed after the try/catch block is finished, but in the second case it has to be closed manually – Petrosyan Alexander Feb 08 '18 at 02:50
  • Then say that it will still remain open after the try/catch block. "resource fis will still exist " does not really make much sense. – tsolakp Feb 08 '18 at 02:56