Search code examples
javaservletstry-catch-finally

Java Finally Not Called when using RequestDispatcher


We have a Java servlet acting as dispatcher for a web app. For each request a database connection is created and then committed / rolled back at the end of the request depending on whether the action was successful or not. It looks something like:

public class WebDispatcher extends HttpServlet {

    protected void processRequest(HttpServletRequest request,
                                  HttpServletResponse response)
                                  throws ServletException, IOException {

        Connection conn = null;

        try {

           // Create connection

        } catch(.....) { 

        } finally {

          // Commit / Rollback connection

        }

    }

}

The problem occurs when there is an exception. For example if they don't have access to a certain action the dispatcher has to redirect them. It does this by using a request dispatcher.

} catch(RoleAuthorizationException rae) {

    request.getRequestDispatcher(.....).forward(request, response);

}

I had assumed that 'finally' would be called but it doesn't seem to be in this case. With each exception we end up losing a connection in the pool. As a workaround we are closing the connection with each exception but why isn't finally being called?


Solution

  • Finally is always called (oracle docs):

    The finally block always executes when the try block exits.

    Check if there is an exception being thrown in the finally block (before the connection is closed).

    See also this answer.