java - Close connection and statement finally -
which better block:
finally { try { con.close(); stat.close(); } catch (sqlexception sqlee) { sqlee.printstacktrace(); } }
or:
finally { try { if (con != null) { con.close(); } if (stat != null) { stat.close(); } } catch (sqlexception sqlee) { sqlee.printstacktrace(); } }
better way use 2nd one, because if exception thrown while initializing con
or stat
, won't initialized, , might left initialized null
. in case, using 1st code throw nullpointerexception
.
also, if on java 7, should consider using try-with-resources
, automatically closes resources. linked tutorial:
the try-with-resources statement ensures each resource closed @ end of statement. object implements java.lang.autocloseable, includes objects implement java.io.closeable, can used resource.
Comments
Post a Comment