1// It was introduced because of some resources used in Java
2// (like SQL connections or streams being difficult to be handled
3// properly; as an example, in java 6 to handle a InputStream
4// properly you had to do something like:
5
6InputStream stream = new MyInputStream(...);
7try {
8 // ... use stream
9} catch(IOException e) {
10 // handle exception
11} finally {
12 try {
13 if(stream != null) {
14 stream.close();
15 }
16 } catch(IOException e) {
17 // handle yet another possible exception
18 }
19}
20// Do you notice that ugly double try? now with try-with-resources
21// you can do this:
22
23try (InputStream stream = new MyInputStream(...)){
24 // ... use stream
25} catch(IOException e) {
26 // handle exception
27}
28
29// and close() is automatically called, if it throws an IOException,
30// it will be supressed (as specified in the Java Language
31// Specification 14.20.3). Same happens for java.sql.Connection
1try (PrintWriter writer = new PrintWriter(new File("test.txt"))) {
2 writer.println("Hello World");
3}