Search code examples
javatry-catch-finally

Using 'finally' to call a method by Design


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.


Solution

  • No, there doesn't seem to be any limitation with your new method approach. Methods can be created to provide flexibility within the code.

    You only have an entityManagerProvider (which you can pass to this new method as a parameter, if calling from other places), and rest you're working with all newly created objects and references; so it is perfect to define the new method and call it wherever you use finally{...}.