How to Properly Handle Exceptions in a JSP/Servlet App?

Solution 1:

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:

<error-page>
    <error-code>500</error-code>
    <location>/error.jsp</location>
</error-page>

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);
}

Solution 2:

Or you can intercept all your exceptions using a servlet:

<!-- WEB-INF/web.xml -->
<servlet>
    <servlet-name>ErrorServlet</servlet-name>
    <servlet-class>com.domain.MyErrorServlet</servlet-class>
</servlet>    
<servlet-mapping>
<servlet-name>ErrorServlet</servlet-name>
    <url-pattern>/error</url-pattern>
</servlet-mapping>
<error-page>
    <exception-type>java.lang.Throwable</exception-type>
    <location>/error</location>
</error-page>

Then in the servlet you can handle the exception like this

public class MyErrorServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response){
       Throwable throwable = (Throwable) request.getAttribute("javax.servlet.error.exception");
       // You can log the exception, send to email, etc
    }
}

Solution 3:

There are a few best practices when it comes to exceptions. Generally you can either handle it, let it bubble up(for unchecked exceptions), log it, or wrap it.

You should avoid catching and throwing exception, instead catch the more specific exception, or create your own exception type and wrap the current exception in that.

Heres a great resource to use as a "What not to do" in terms of exceptions: http://today.java.net/article/2006/04/04/exception-handling-antipatterns