Answers for "java try with resources"

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
Posted by: Guest on December-11-2020
3

java try with resources

try (PrintWriter writer = new PrintWriter(new File("test.txt"))) {
  writer.println("Hello World");
}
Posted by: Guest on October-21-2020

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language