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:
public static void main(String[] args) { 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(); } } }As seen here the number of try catches is enormous. If I were to write it in the Java7 style:
public static void main(String[] args) { try (Connection conn = DriverManager.getConnection("DB_URL", "USER", "PASS")) { conn.commit(); } catch (SQLException exception) { // conn.rollback(); } }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)
Use a try catch within the try catch
public static void main(String[] args) { try(Connection conn = DriverManager.getConnection("DB_URL", "USER", "PASS")) { try { conn.commit(); } catch (SQLException e) { try { conn.rollback(); } catch (SQLException rollbackException) { rollbackException.printStackTrace(); } } } }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.
No comments:
Post a Comment