Which is better for finally 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();
}
}
None of them are good enough. Use this:
And call it like
closeQuietly(stat, con);
Or use java 7's
try-with-resource
:If there is a possibility either is
null
, you must check that. If the possibility does not exist, there is no valid reason to check for it.Also, you can make your code slightly better readable by omitting some single-statement brackets:
I would go with the second option, but adding a second nested
finally
block, just to make sure that bothcon
andstat
objects are marked for garbage collection:As of Java 7, you don't need any more use the finallyl block to close a Connection or Statement object. Instead you can make use of the new features called 'try-with-resources'.
First you declare a Connection and Statament objects by using the new syntax for a try-catch block as follows:
Doing so, you won't need to worry to close explicitly the linkage with the database in a finally block because the jvm will do it for you.
Have nice coding....
Better way to use is the 2nd one, because if an exception is thrown while initializing
con
orstat
, they won't be initialized, and might be left initialized tonull
. In that case, using the 1st code will throwNullPointerException
.Also, if you are already on Java 7, you should consider using
try-with-resources
, which automatically closes the resources. From the linked tutorial: