In a try-catch-finally
situation what is the proper way of handling finally
when it comes to calling a method?
The reason why I ask is a Service Implementation class that makes DB calls might have a finally
clause in every method.
If I am to use the DRY approach I don't want the finally
clause to keep repeating the same code.
For example
try {
// DB call
} catch (DAOException e) {
// Error messages etc
} finally {
// entityMangerProvider is a field
EntityManager entityManager = entityManagerProvider.get();
EntityTransaction transaction = entityManager.getTransaction();
if (entityManager.isOpen()) {
if (transaction.isActive()) {
transaction.rollback();
}
entityManager.close();
}
}
The finally
above gets repeated through out. Is it proper to do something like this
private void closeEntityManager() {
EntityManager entityManager = entityManagerProvider.get();
EntityTransaction transaction = entityManager.getTransaction();
if (entityManager.isOpen()) {
if (transaction.isActive()) {
transaction.rollback();
}
entityManager.close();
}
}
and then do this
try {
// DB call
} catch (DAOException e) {
// Error messages etc
} finally {
closeEntityManager();
}
Are there any drawbacks to this approach? Is there a better way of avoiding repeating the finally clause over and over again.
Project is on Java 7, if it matters.