How to properly handle exceptions in a JSP / Servlet application?


How do you properly handle errors encountered in a servlet? Right now, the app that I inherited (uses only plain JSP/Servlet) has a superclass called Controller which extends HttpServlet and which all other servlets extend from. In that Controller class is a try and catch block like the following:

try {
    // execute doPost or doGet here
} catch (Exception e) {
    // show a generic error page

Is this the proper way of doing it? It seems clunky and doesn't seem to always work. I'm only an intern so I don't have a lot of experience with this. Any advice? I'm trying to make the app for robust..

The standard thing to do is have your Servlet's doXxx() method (eg. doGet(), doPost(), etc.) throw a ServletException and allow the container to catch and handle it. You can specify a custom error page to be shown in WEB-INF/web.xml using the <error-page> tag:


If you end up catching an Exception you can't elegantly handle, just wrap it in a ServletException like this:

try {
    // code that throws an Exception
} catch (Exception e) {
    throw new ServletException(e);