Jefferson
Jefferson

Reputation: 399

Selective catch for a closeable resource

This is more of a syntax / structuring issue. I'm working with JDBC: Statement and ResultSet, which means SQLExceptions are being thrown everywhere.

My code looks like this:

private static final String MY_QUERY = "SELECT * FROM MY_TABLE";

public void lookAtMetadata() throws SQLException { 
  try (Statement myStatement = getStatement) 
  {
    try (ResultSet myResultSet = myStatement.executeQuery(MY_QUERY)) 
    {
      ResultSetMetadata metadata = myResultSet.getMetaData();
      // do other stuff with metadata
    }
  }
}

So far so good. But I want to throw a special Exception when myStatement.executeQuery(MY_QUERY) fails, like so:

ResultSet myResultSet = null;
try 
{
  myResultSet = myStatement.executeQuery(MY_QUERY);
  // get metadata and do stuff 
} catch (SQLException e) 
{
  throw new MySpecialException(e);
} finally 
{
  if (myResultSet != null) myResultSet.close();
}

The problem is, other operations involving ResultSetMetaData may also throw an SQLException, and I do NOT want to wrap those with MySpecialException.

Is there a way such that I can catch only the SQLException coming from query execution, and letting other SQLExceptions be thrown to the method caller? I would also like to properly close ResultSet.

Upvotes: 0

Views: 39

Answers (1)

Vasan
Vasan

Reputation: 4956

Use a nested try structure, with the inner try wrapping only the executeQuery. Add the catch handler to this inner try. Leave the outer try without a catch handler, so that it will propagate all other SQLExceptions as-is

ResultSet myResultSet = null;
try 
{
  try {
      myResultSet = myStatement.executeQuery(MY_QUERY);
  } catch (SQLException e) {
      throw new MySpecialException(e);
  }
  // get metadata and do stuff 
} finally 
{
  if (myResultSet != null) myResultSet.close();
}

Upvotes: 2

Related Questions