私は現在、データベースで多くの作業を行うプロジェクトに取り組んでいます。
コードで何度も何度も再利用した中心的な慣用句の 1 つを次に示します。
私の質問は、getTransformedResults メソッドの各ステップで例外を処理するより良い方法はありますか? これは SQLExceptions を処理する適切な方法ですか、それともこれを行うためのより良い、より簡潔な方法はありますか?
ご意見ありがとうございます。
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;
}