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.

4

1 回答 1

3

使用嵌套的 try 结构,内部的 try 仅包装executeQuery. 将 catch 处理程序添加到此内部尝试。让外部 try 不使用 catch 处理程序,以便它SQLException按原样传播所有其他 s

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();
}
于 2018-04-17T19:21:48.770 回答