Coding Hell

Programming and stuff.

Java 7: Try-with-resources

A nice Java 7 feature is the new try-with-resources statement.

When you did some SQL things back in the Java 6 days, you often ended up with something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
try {
  Connection con = createConnection();
  // do something
  Statement stmt = null;
  try {
    stmt = con.createStatement();
    ResultSet rs = stmt.executeQuery("SELECT ...");
    // do something with rs
    rs.close();
  } catch (SQLException e) {
    e.printStackTrace();
  } finally {
    if (stmt != null) {
      stmt.close();
    }
  }
} finally {
  con.close();
}

Now with Java 7, this got a lot easier and shorter:

1
2
3
4
5
6
7
8
9
try (Connection con = createConnection()) {
  // do something
  try (Statement stmt = con.createStatement();
       ResultSet rs = stmt.executeQuery("SELECT ...")) {
    // do something with rs
  } catch (SQLException e) {
    e.printStackTrace();
  }
}

Awesome!

If you want to write a class that supports this syntax, you may take a look a the AutoClosable interface.

Comments