Resource handling with try-with-resources

The constructor shows something interesting that we haven't talked about--try-with-resources. Prior to Java 8, you might have written something like this:

    public SunagoProperties(int a) { 
      InputStream input = null; 
      try { 
        input = new FileInputStream(FILE); 
        props.load(input); 
      } catch  (IOException ex) { 
        // do something 
      } finally { 
          if (input != null) { 
            try { 
                input.close(); 
            } catch (IOException ex1) { 
                Logger.getLogger(SunagoProperties.class.getName()) 
                  .log(Level.SEVERE, null, ex1); 
            } 
          } 
        } 
    } 

This preceding, incredibly verbose code declares an InputStream outside the try block, then does some work with it in the try block. In the finally block, we try to close the InputStream, but we first have to check ...

Get Java 9 Programming Blueprints 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.