The try-with-resource statement

The try-with-resource statement previously required a new variable to be declared for each resource in the statement when a final variable was used. Here is the syntax for the try-with-resource statement prior to Java 9 (in Java 7 or 8):

    try ( // open resources )     {      // use resources    } catch (// error)     {  // handle exceptions    }    // automatically close resources

Here is a code snippet using the preceding syntax:

    try ( Scanner xmlScanner = new Scanner(new File(xmlFile));    {       while (xmlScanner.hasNext())       {          // read the xml document and perform needed operations       }      xmlScanner.close();    } catch (FileNotFoundException fnfe)      {         System.out.println("Your XML file was not found.");      }

Now, with Java 9, the try-with-resource ...

Get Java 9: Building Robust Modular Applications now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.