1

I recently started with project and I see following pattern is used a lot in several classes to close connection, statement and result set.

finally
    {
      result.close();
      close();
    }

result.close() invokes following method.

public void close() throws SQLException
  {

    SQLException resultException = null;
    if (resultSet != null)
    {
      try
      {
        resultSet.close();
      }
      catch (SQLException e)
      {
        resultException = e;
      }
    }

    if (statement != null)
    {
      try
      {
        statement.close();
      }
      catch (SQLException e)
      {
        resultException = e;
      }
    }

    resultSet = null;
    statement = null;
    if (resultException != null)
    {
      throw resultException;
    }
  }

close() invokes following method.

 public void close() throws SQLException
  {
    if (connection != null && !connection.isClosed())
    {
      connection.close();
    }
    connection = null;
  }

I think there is a possibility of connection leak, if an exception is thrown while closing statement and resultset. Can I just catch it and log and move to closing connecton? Or what should I do if it throw SQLException?

pavithraCS
  • 709
  • 6
  • 23
  • Exception while closing statements and result sets will probably be only because the connection is already closed, So just log it(just in case) and move on. – Siva Rahul Jun 01 '22 at 10:50
  • 2
    => try-with-resources !!! – Seelenvirtuose Jun 01 '22 at 10:51
  • You *really* you should learn *try-with-resources* syntax. See [tutorial](https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html) by Oracle, free-of-cost. – Basil Bourque Jun 01 '22 at 19:07

0 Answers0