我有以下代码:
public class Main {
public static void main(String[] args) throws SQLException {
try (
Connection conn = DBUtil.getConnection(DBType.HSQLDB);
Statement stmt = conn.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet rs = stmt.executeQuery("SELECT * FROM tours");
) {
DBUtil.getConnection();
} catch (SQLException e) {
DBUtil.processException(e);
}
}
}我使用此代码从数据库获取数据。我的问题是不允许我使用Java1.7编译器,而必须使用1.6。如何翻译try- with -resources-code以在1.6编译器中使用?在这个特殊的try块中到底发生了什么?
发布于 2014-05-12 22:44:43
甲骨文解释了尝试资源的工作原理here
它的TL;DR是:
在Java 1.6中没有简单的方法可以做到这一点。问题是没有异常的被抑制的字段。你可以忽略这一点,并硬编码当try和close抛出不同的异常时发生的事情,或者创建自己的包含受抑制字段的异常子层次结构。
在第二种情况下,上面的链接给出了正确的方法:
AutoClose autoClose = new AutoClose();
MyException myException = null;
try {
autoClose.work();
} catch (MyException e) {
myException = e;
throw e;
} finally {
if (myException != null) {
try {
autoClose.close();
} catch (Throwable t) {
myException.addSuppressed(t);
}
} else {
autoClose.close();
}
} 等同于
try (AutoClose autoClose = new AutoClose()) {
autoClose.work();
}如果您想让它变得更简单,而又不想创建一大堆新的异常类,那么您必须决定在finally (t或e)中抛出catch子句中的内容。
PS。在上面的链接中也讨论了在try中处理多个变量声明。而且你需要的代码数量是惊人的。在Java1.6中,大多数人通过不处理finally块中的异常并使用nullcheck来走捷径。
发布于 2014-05-12 22:42:40
如下所示:
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
conn = DBUtil.getConnection(DBType.HSQLDB);
stmt = conn.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
rs = stmt.executeQuery("SELECT * FROM tours");
} catch (SQLException e) {
DBUtil.processException(e);
} finally {
if(conn != null) {
conn.close();
}
if(stmt != null) {
stmt.close();
}
if(rs != null) {
rs.close();
}
}发布于 2016-11-16 00:30:33
我建议使用apache的commons-dbutils库,它有带有close和closeQuietly方法的DBUtils类。代码将如下所示:
import org.apache.commons.dbutils.DBUtils;
...
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
conn = myOwnUtil.getConnection();
stmt = conn.createStatement();
rs = stmt.executeQuery( "SELECT * FROM table" ); // or any other custom query
} catch ( SQLException e ) {
<<handle exception here>>;
} finally {
DBUtils.closeQuietly( conn );
DBUtils.closeQuietly( stmt );
DBUtils.closeQuietly( rs );
// or simply use DBUtils.close( conn, stmt, rs );
}请注意,closeQuietly不会抛出异常,而close可能会强制转换SQLException,因此请根据您自己的用例调整代码。
如果你想关闭流,你可以使用带有IOUtils类的apache的commons-io,这个类也有close和closeQuietly。
https://stackoverflow.com/questions/23611940
复制相似问题