嵌套尝试资源与单一

时间:2015-02-12 02:32:46

标签: java nested try-catch

所以我遇到了一些代码,并想知道使用嵌套的try-with-resource语句和使用单个try-with-resource与多个资源之间的区别是什么?

 private void doEverythingInOneSillyMethod(String key)
      throws MyAppException
    {
      try (Connection db = ds.getConnection()) {
        db.setReadOnly(true);
        ...
        try (PreparedStatement ps = db.prepareStatement(...)) {
          ps.setString(1, key);
          ...
          try (ResultSet rs = ps.executeQuery()) {
            ...
          }
        }
      } catch (SQLException ex) {
        throw new MyAppException("Query failed.", ex);
      }
    }

VS

private void doEverythingInOneSillyMethod(String key)
        throws MyAppException {
    try (Connection db = ds.getConnection();
            PreparedStatement ps = db.prepareStatement(...);
            ResultSet rs = ps.executeQuery();) {

        db.setReadOnly(true);

        ps.setString(1, key);
    } catch (SQLException ex) {
        throw new MyAppException("Query failed.", ex);
    }
}

前者有什么好处吗?

0 个答案:

没有答案