JDK 7 has several enhancements to the try-catch construct. Try with resources allows for ensuring that resources are closed and freed up without the need to explicitly call the close function. Any class implementing java.lang.AutoCloseable can be automatically closed without the need for a finally section in the try block.
The syntax is a try with parens and the resources to automatically close out inside the parens.
try ( resources ) { code } catch (exception) { }
snippet 1 shows the syntax for try with resources:
try (
BufferedReader reader = new BufferedReader(
new FileReader("c:/dev/jdk7test/t1.ofx"));
BufferedWriter writer = new BufferedWriter(
new FileWriter("c:/dev/jdk7test/output.txt"))
) {
// read and write
}
Another change to try is that the catch can now handle multiple exception types in one block. Multiple catch blocks are optional and still work fine if you prefer to separate the handling. Just separate the exception types with | .
Snippet 2 catch with multiple exception types:
catch (java.io.FileNotFoundException | java.io.IOException ex) {
System.out.println(ex.getMessage());
}
Lastly here is a small simple class that shows both features in action.
package jdk7test;
import java.io.*;
public class Jdk7TryWithResourcesTest {
public static void main(String[] args) {
Jdk7TryWithResourcesTest test = new Jdk7TryWithResourcesTest();
test.execute();
}
public void execute() {
try (
BufferedReader reader = new BufferedReader(new FileReader("c:/dev/jdk7test/t1.ofx"));
BufferedWriter writer = new BufferedWriter(new FileWriter("c:/dev/jdk7test/output.txt"))
) {
String line;
while ((line = reader.readLine()) != null){
writer.write(line);
}
} catch (java.io.FileNotFoundException | java.io.IOException ex) {
System.out.println(ex.getMessage());
}
}
}
Standard disclaimer - At the time of posting I believe all information contained to be accurate but there is absolutely no warranty or guarantee.