I get an exception that the database is locked and I try to close connection and statement, but here is the problem unreachable statement in try block.
public static ResultSet getData (String query){
try {
Connection conn = ConnectionProvider.connect();
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(query);
return rs;
try {
conn.close();
st.close();
rs.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
return null;
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
System.out.println(e);
return null;
}
CodePudding user response:
Everything you do after the first return statement in the outer try block can never be reached. The second try block will never be executed, therefore you have some unreachable code here. I think what you want to do is this:
try {
Connection conn = ConnectionProvider.connect();
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(query);
try {
conn.close();
st.close();
rs.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
return null;
}
return rs;
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
System.out.println(e);
return null;
}
Although I will say that this may just not be the correct place to use the try-catch. Maybe what you should do here is throw the possible exceptions back to whoever calls this method instead - usually nested try-catch blocks are very rarely actually used/needed in this way. Also if you encounter an exception, you just return null, instead of handling what this means for the rest of your application. What you could also try is, assuming that at this point your query was successful:
try {
Connection conn = ConnectionProvider.connect();
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(query);
try {
conn.close();
st.close();
rs.close();
} catch (Exception e) {
throw e;
} finally {
return rs;
}
} catch (Exception e) {
throw e;
}
Though for this approach you should really think about what you need to happen in each error case. As an additional side note, even though I'm aware that many people ignore this: Always try to use the proper class for the Exceptions you expect in a catch-block, and if it's only for readabilities sake.
CodePudding user response:
There are several things to improve in the piece of code you post.
First, you need to close the resources (Connection, Statement and ResultSet) in reverse order with respect to the opening order. So, first you should close the ResultSet, second the Statement, and finally the Connection.
Closing in the order you are doing might cause problems when closing Statement / ResultSet with the Connection already closed.
By other hand, starting in Java 7, you have the try-with-resources construct, that closes resources for you. You can take a look at The try-with-resources Statement docs.