Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try
{
conn = geting the connection object ( using DriverManager.getConnection() method or using connection pool)
stmt = conn.createStatement ("select ...");
// some other logic here
}
catch (SQLException e)
{
// handling the exceptions
}
finally
{
}
Here my question is while closing the connection object in the following cases what are the problems it will come.
Assume if there is no exception occurred, in try block there it self closing the connection object.
try {
// same above code
stmt.close();
conn.close();
} catch(Exception ex) {
// handling the exceptions
} finally {
}
If some exception is occured so it will goes to catch block, there it self closing the connection object.
try {
// same above code
} catch(Exception ex) {
// handling the exceptions
stmt.close();
conn.close();
} finally {
}
Closing the connection object in finally block.
try {
// same above code
} catch(Exception ex) {
// handling the exceptions
} finally {
stmt.close();
conn.close();
}
Note: Please don't say closing the connection object in finally block is good. I know that one. If i keep the close connection in try block, catch block is there any problems please explain.
It is recommended to close the connection in the finally
block because if you have multiple catch
blocks (as you should: you should never catch generic Exception
) you will not have to re-write the closing statements.
A finally
block will always be executed after a try
, no matter what happens. So if you get a NullPointerException
, or some other exception you didn't handle, with the finally
block you will be sure that your resources are closed properly.
But if you are on java 7, I'd suggest to use the try-with-resources block
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