java - How to Correctly Close Resources -


as cleaning code, findbugs pointed me bit of jdbc code uses connection, callablestatement, , resultset objects. here's snippet code:

callablestatement cstmt = getconnection().preparecall("..."); ... resultset rs = cstmt.executequery();  while ( rs.next() ) {     ... }  cstmt.close(); rs.close(); con.close(); 

findbugs pointed out these should within block. started refactoring code , started wonder how handle code within block.

it's possible creation of callablestatement of connection objects throw exception, leaving resultset object null. when try close resultset, i'd nullpointerexception , connection would, in turn, never closed. indeed, this thread brings same concept , shows wrapping close() invocations in null check idea.

but other possible exceptions? according java api spec, statement.close() can throw sqlexception "if database error occurs". so, if callablestatement not null , can call close() on it, might still exception , not have chance close other resources.

the "fail safe" solution can think of wrap each close() invocation in own try/catch block, this:

finally {      try {         cstmt.close();     } catch (exception e) { /* intentionally swallow  exception */ }      try {         rs.close();     } catch (exception e) { /* intentionally swallow  exception */ }      try {         con.close();     } catch (exception e) { /* intentionally swallow  exception */ }  } 

boy, if doesn't awful. there better way go this?

i think best answer has being mentioned, thought interesing mention consider new jdk 7 feature of autoclosable resources.

try{     try(connection conn = drivermanager.getconnection("jdbc:mysql://localhost/hrdb", "obiwan", "kenobi");          statement stm = conn.createstatement();          resultset rs = stm.executequery("select name department")) {          while(rs.next()){             system.out.println(rs.getstring("name"));         }      }  }catch(sqlexception e){     //you might wanna check e.getsuppressed()     //log, wrap, rethrow desired. } 

not of can migrate jdk 7 now, can start playing developer preview, offer interesting way of doing things , may deprecate other approaches in near future.


Comments

Popular posts from this blog

python - TypeError: start must be a integer -

c# - DevExpress RepositoryItemComboBox BackColor property ignored -

django - Creating multiple model instances in DRF3 -