0

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.

Jefferson
  • 379
  • 2
  • 4
  • 11

1 Answers1

2

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();
}
Vasan
  • 4,810
  • 4
  • 20
  • 39