What’s wrong with this java code?
by Robert FullerCan you spot the bug in this code?
01 Connection conn=null; 02 Statement st = null; 03 ResultSet rs = null; 04 try{ 05 conn = getConnection(); 06 st = conn.createStatement(); 07 rs = conn.executeQuery("select foo from bar"); 08 ... 09 }finally{ 10 if(rs!=null) rs.close(); 11 if(st!=null) st.close(); 12 if(conn!=null) conn.close(); 13 }
Answer: If an SQLException is thrown at line 10 or 11, line 12 will not be executed. If line 12 is not executed some resources may be lost.
Yes, the likelihood of an exception being thrown at line 10 or 11 is low, but good java programmers will avoid leaking resources by defensive use of try-catch blocks. Use the pattern of starting the try block immediately after allocating a resource. Here’s a better way to write the same block of code:
01 Connection conn = getConnection(); 02 try{ 03 Statement st = conn.createStatement(); 04 try{ 05 ResultSet rs = conn.executeQuery("select foo from bar"); 06 try{ 07 ... 08 }finally{ 10 rs.close(); 11 } 12 }finally{ 13 st.close(); 14 } 15 }finally{ 16 conn.close(); 17 }