what is try with resources code example
Example 1: 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
Example 2: java try with resources
try (PrintWriter writer = new PrintWriter(new File("test.txt"))) {
writer.println("Hello World");
}