Search This Blog

Saturday, 16 January 2016

try with resource - dealing with failures

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:
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.

2 comments:

  1. Blogging is incredible and every blogger playing a great role to introduce new things in blogging. I always like to fly on different blogs and read the strategies of different blogger to understand the blogging in more depth. Being a bloggers I really appreciate your works and no doubt your blog is awesome.
    Love from Asad Niazi

    ReplyDelete
  2. If you need your ex-girlfriend or ex-boyfriend to come crawling back to you on their knees (even if they're dating somebody else now) you got to watch this video
    right away...

    (VIDEO) Text Your Ex Back?

    ReplyDelete