Reputation: 9
I have two question for my problem .
1.Is it necessary to include a catch block in my method if I have a throw?
2.Is it necessary to try - finally block in my method to handle connection.close?
public int count() throws SQLException {
XAConnection xaConnection=null;
Statement statement=null;
ResultSet resultSet=null;
int count =0;
try{
String SQL = "SELECT count(*) FROM book";
xaConnection = dbService.getConnection();
statement = xaConnection.getConnection().createStatement();
resultSet = statement.executeQuery(SQL);
if(resultSet.next()){
count = resultSet.getInt(1);
}
}
finally {
if(xaConnection!= null){
xaConnection.close();
}
if(resultSet != null){
resultSet.close();
}
if(statement != null){
statement.close();
}
}
return count;
}
Upvotes: 0
Views: 205
Reputation: 5754
1. Is it necessary to include a catch block in my method if I have a throw?
No, it's fine to do try-finally. Allowed combinations include try-catch, try-finally, and try-catch-finally.
There's also an option called "try with resources" which looks like a standalone "try" but behind the scenes it behaves like try-finally. There are some examples in the Java Language Spec section 14.20.3.1.
2. Is it necessary to try - finally block in my method to handle connection.close?
No, it isn't strictly necessary – Java will allow you to do it. However, opening connections without closing them will lead to problems over time, so yes you should close them.
Here's an edit to your posted code showing how you could clean things up by using try-with-resources.
xaConnection
is closed – it isn't possible to do try-with on javax.sql.XAConnection
because it doesn't implement java.lang.AutoCloseable
.import javax.sql.XAConnection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public int count() throws SQLException {
String SQL = "SELECT count(*) FROM book";
XAConnection xaConnection = dbService.getConnection();
try {
try (Statement statement = xaConnection.getConnection().createStatement()) {
try (ResultSet resultSet = statement.executeQuery(SQL)) {
if (resultSet.next()) {
return resultSet.getInt(1);
}
}
}
return 0;
} finally {
if (xaConnection != null) {
xaConnection.close();
}
}
}
Upvotes: 2