Search code examples
javasyntaxcoding-styletry-catch

Regarding java's try/catch syntax; are these blocks equivalent?


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!


Solution

  • 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.