【问题标题】:Selective catch for a closeable resource可关闭资源的选择性捕获
【发布时间】:2018-04-17 19:15:30
【问题描述】:

这更多是语法/结构问题。 我正在使用 JDBC:StatementResultSet,这意味着 SQLExceptions 被到处抛出。

我的代码如下所示:

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
    }
  }
}

到目前为止一切顺利。 但是我想在myStatement.executeQuery(MY_QUERY) 失败时抛出一个特殊的异常,如下所示:

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();
}

问题是,涉及ResultSetMetaData 的其他操作也可能会抛出SQLException,我不想用MySpecialException 包装这些操作。

有没有办法让我只捕获来自查询执行的SQLException,而让其他SQLExceptions 被抛出给方法调用者?我还想正确关闭ResultSet

【问题讨论】:

    标签: java checked-exceptions autocloseable


    【解决方案1】:

    使用嵌套的 try 结构,内部的 try 仅包装 executeQuery。将 catch 处理程序添加到此内部尝试。在没有 catch 处理程序的情况下保留外部尝试,以便它将按原样传播所有其他 SQLExceptions

    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();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-30
      • 2019-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多