我有一个带有许多方法的 DAO 类,这些方法有很多重复的代码,如下所示: -
public void method1(...) {
Connection conn = null;
try {
//custom code here
} catch (SQLException e) {
LOG.error("Error accessing the database.", e);
throw new DatabaseException();
} catch (QueryNotFoundException e) {
LOG.error("Error accessing the database.", e);
throw new DatabaseException();
} finally {
if (conn != null)
connectionPool.returnConnection(conn);
}
public void method2(...) {
Connection conn = null;
try {
//different custom code here
} catch (SQLException e) {
LOG.error("Error accessing the database.", e);
throw new DatabaseException();
} catch (QueryNotFoundException e) {
LOG.error("Error accessing the database.", e);
throw new DatabaseException();
} finally {
if (conn != null)
connectionPool.returnConnection(conn);
}
我想重组这个类,把try,catch,finally放在一个地方以避免重复。我将如何做到这一点?