Java 使用 RequestDispatcher 时最终未调用

Java Finally Not Called when using RequestDispatcher

我们有一个 Java servlet 作为网络应用程序的调度程序。对于每个请求,都会创建一个数据库连接,然后根据操作是否成功在请求结束时提交/回滚。它看起来像:

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

        }

    }

}

出现异常时出现问题。例如,如果他们无权访问某个操作,则调度员必须重定向他们。它通过使用请求调度程序来做到这一点。

} catch(RoleAuthorizationException rae) {

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

}

我原以为 'finally' 会被调用,但在这种情况下似乎并非如此。对于每个异常,我们最终都会丢失池中的连接。作为解决方法,我们将关闭每个异常的连接,但为什么最终没有被调用?

最后 is always called(oracle 文档):

The finally block always executes when the try block exits.

检查 finally 块中是否抛出异常(在连接关闭之前)。

另见 this answer