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();
}
}
Yes it does, Connection. close API says "Releases this Connection object's database and JDBC resources immediately instead of waiting for them to be automatically released".
The finally block in java is used to put important codes such as clean up code e.g. closing the file or closing the connection. The finally block executes whether exception rise or not and whether exception handled or not. A finally contains all the crucial statements regardless of the exception occurs or not.
The finally keyword is used to execute code (used with exceptions - try.. catch statements) no matter if there is an exception or not.
The finally block is a place to put any code that must execute, whether the try-block raised an exception or not. The syntax of the try-finally statement is this − try: You do your operations here; ...................... Due to any exception, this may be skipped.
Better way to use is the 2nd one, because if an exception is thrown while initializing con
or stat
, they won't be initialized, and might be left initialized to null
. In that case, using the 1st code will throw NullPointerException
.
Also, if you are already on Java 7, you should consider using try-with-resources
, which automatically closes the resources. From the linked tutorial:
The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With