In the previous post we saw the try-with-resource statements and how the execution flows. Here I decided to look at the java.sql.Connection class which also implements the AutoCloseable interface.
In the old style code:
Use a try catch within the try catch
In the old style code:
publicstatic void main(String[] args) {As seen here the number of try catches is enormous. If I were to write it in the Java7 style:
Connection conn = null;
try {
conn = DriverManager.getConnection("DB_URL", "USER", "PASS");
conn.commit();
} catch (SQLException exception) {
try {
conn.rollback();
} catch (SQLException e) {
e.printStackTrace();
}
} finally {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
publicstatic void main(String[] args) {Code is super smaller. But we have a problem. How do we rollback ?I had this problem when working with Neo4j and was flummoxed for some time. As the scope of the resource(Connection in above example) is limited to the try block, how do I rollback when an exception occurs? A search on stack overflow gave me the answer (as always)
try (Connection conn = DriverManager.getConnection("DB_URL", "USER", "PASS")) {
conn.commit();
} catch (SQLException exception) {
// conn.rollback();
}
}
Use a try catch within the try catch
publicstatic void main(String[] args) {Here an inner try catch is used to manage the internal behavior while the outer try looks after the resource management.So now we can combine the rollback behavior with the try-with-resource behavior thus simplifying the code.
try(Connection conn = DriverManager.getConnection("DB_URL", "USER", "PASS")) {
try {
conn.commit();
} catch (SQLException e) {
try {
conn.rollback();
} catch (SQLException rollbackException) {
rollbackException.printStackTrace();
}
}
}
}