我目前正在开发一个需要大量使用数据库的项目。
我在代码中多次重复使用的一个核心惯用法如下。
我的问题是,是否有更好的方法来处理 getTransformedResults 方法每一步的异常?这是处理 SQLException 的正确方法,还是有更好、更简洁的方法?
感谢您的意见!
public ResultType handleResultSet(ResultSet rs);
public ResultType getTransformedResults(String query) throws SQLException {
ResultType resultObj = new ResultType();
Connection connection = null;
try {
connection = dataSource.getConnection();
} catch (SQLException sqle) {
// cleanup
throw sqle;
}
Statement stmt = null;
try {
stmt = connection.createStatement();
} catch (SQLException sqle) {
try { connection.close() } catch (SQLException dontCare) {}
// cleanup
throw sqle;
}
ResultSet rs = null;
try {
ResultSet rs = stmtm.executeQuery(query);
resultObj = handleResultSet(rs);
} catch (SQLException sqle) {
// cleanup
throw sqle;
} finally {
if (rs != null) try { rs.close() } catch (SQLException dontCare) {}
try { stmt.close() } catch (SQLException dontCare) {}
try { connection.close() } catch (SQLException dontCare) {}
}
return resultObj;
}
最佳答案
Java 7 有一些您可能会欣赏的结构,我认为您可以使用 try/finally 而不使用 catch(它模仿您的 catch 和 re throw)。
此外,由于您已经捕获并处理了 SQL 异常,也许您应该将其作为其他内容重新抛出(也许作为运行时异常),这样可以更轻松地在主入口点捕获所有运行时异常,而不是而不是每次访问数据库时都必须处理异常。
关于java - 有没有更好的方法来处理从某些数据源抛出的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11455815/