Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
Ask Question
try {
connection = createConnection();
String sql = String.format(STRING_FOR_PROCEDURE, name);
connection.createStatement().execute(sql);
connection.commit();
} catch (Exception e) {
throw new DatabaseServiceException(e.getMessage(), e);
} finally {
closeConnection(connection);
I suppose sonar wants me to close connection in block "finally" with something like this:
connection.close();
But I use custom method for this which is:
protected void closeConnection(Connection connection) {
try {
if (connection != null) {
connection.close();
} catch (SQLException ex) {
LOGGER.log(Level.SEVERE, null, ex);
This method needs to be used in current class. But I receive sonar blocker "use try-with-resources or close this statement in a "finally" clause".
Any ideas how to fix it?
–
–
–
Notice that your error is “use try-with-resources or close this statement in a "finally" clause.”
The problem isn’t how you close your Connection. The problem is that you aren’t closing your Statement.
Connection connection = null;
Statement statement = null;
try {
connection = createConnection();
String sql = String.format(STRING_FOR_PROCEDURE, name);
statement = connection.createStatement();
statement.execute(sql);
connection.commit();
} catch (Exception e) {
throw new DatabaseServiceException(e.getMessage(), e);
} finally {
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
Logger.log(Level.SEVERE, "Could not close Statement.", e);
closeConnection(connection);
Remember that the statement needs to be closed before the Connection is closed.
Sonar helps in designing proper code but sometimes if you are well aware we can ignore the warning.. but yes can you do this?
Connection connection = null;
try {
connection = createConnection();
String sql = String.format(STRING_FOR_PROCEDURE, name);
connection.createStatement().execute(sql);
connection.commit();
} catch (Exception e) {
throw new DatabaseServiceException(e.getMessage(), e);
} finally {
try {
if (connection != null) {
connection.close();
} catch (SQLException ex) {
LOGGER.log(Level.SEVERE, null, ex);
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.