try vs try() java code example

Example: difference between try catch and try with resources

// It was introduced because of some resources used in Java 
// (like SQL connections or streams being difficult to be handled 
// properly; as an example, in java 6 to handle a InputStream 
// properly you had to do something like:

InputStream stream = new MyInputStream(...);
try {
    // ... use stream
} catch(IOException e) {
   // handle exception
} finally {
    try {
        if(stream != null) {
            stream.close();
        }
    } catch(IOException e) {
        // handle yet another possible exception
    }
}
// Do you notice that ugly double try? now with try-with-resources 
// you can do this:

try (InputStream stream = new MyInputStream(...)){
    // ... use stream
} catch(IOException e) {
   // handle exception
}

// and close() is automatically called, if it throws an IOException, 
// it will be supressed (as specified in the Java Language 
// Specification 14.20.3). Same happens for java.sql.Connection

Tags:

Java Example