When a servlet generates an error developers can handle those exceptions in various ways. For example, when user tries a URL that does not map to a servlet the user typically gets a 404 page. With the error listing in the deployment descriptor, we can handle those exceptions. In this tutorial, we will handle these exceptions in the Servlet.
An exception is an event, which occurs during the execution of a program, which disrupts the normal flow of the program’s instructions. The process of converting the system error messages into user-friendly error messages is known as Exception Handling. There are two main mechanisms of exception handling in Java Web Application:
- Programmatically exception handling mechanism: When using try and catch block in the Java code (Servlet or Filter class) to handle exceptions.
- Declarative exception handling mechanism: When using the XML tags in the web.xml deployment descriptor file for web application to handle the exception. This mechanism is useful if exception is common for more than one servlet program.
Declarative exception handling mechanism
A customized content can be returned to a user when a servlet generates an error. Developers can do that by adding the <error-page /> elements in the web.xml. The following table describes the elements developers can define within an error-page element.
Element |
Required or Optional |
Description |
<error-code> |
Optional |
A valid HTTP error code. For e.g. 500 etc |
<exception-type> |
Optional |
A fully-qualified class name of a Java exception type |
<location> |
Required |
The location of the resource which is displayed to the user in case of an error. For e.g. /error.html , /error.jsp , /error |
Request Attributes Related to Error Information
If the destination in the <location> is a servlet or a JSP page:
- The original request and response objects are passed to the destination
- The request path and the attributes are set as if a forward to the error resource had been performed
- The following request attributes are set:
- javax.servlet.error.status_code of type java.lang.Integer.
- javax.servlet.error.exception_type of type java.lang.Class.
- javax.servlet.error.message of type java.lang.String.
- javax.servlet.error.exception of type java.lang.Throwable.
- javax.servlet.error.request_uri of type java.lang.String.
- javax.servlet.error.servlet_name of type java.lang.String.
Types of Error a Servlet/Filter can Throw
A servlet or filter may throw the following exceptions during the processing of a request:
- Unchecked Exceptions i.e. lang.RuntimeException, Error, and subclasses
- servlet.ServletException or subclasses
- io.IOExceptionor subclasses
Note: All other exceptions should be wrapped in javax.servlet.ServletException.
Web.xml tags for declaring error handling
<web-app ...> .... <error-page> <exception-type>java.lang.ArithmeticException</exception-type> <location>/errorHandler</location> </error-page> .... </web-app>
Servlet Class for handling exception
@WebServlet(name = "errorHandlerServlet", urlPatterns = {"/errorHandler"}, loadOnStartup = 1) public class ErrorHandlerServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { PrintWriter writer = resp.getWriter(); Exception exception = (Exception) req.getAttribute( "javax.servlet.error.exception"); writer.printf("exception: %s%n", exception); Class exceptionClass = (Class) req.getAttribute( "javax.servlet.error.exception_type"); writer.printf("exception_type: %s%n", exceptionClass); Integer code = (Integer) req.getAttribute( "javax.servlet.error.status_code"); writer.printf("status_code: %s%n", code); String errorMessage = (String) req.getAttribute( "javax.servlet.error.message"); writer.printf("message: %s%n", errorMessage); String requestUri = (String) req.getAttribute( "javax.servlet.error.request_uri"); resp.getWriter().printf("request_uri: %s%n", requestUri); String servletName = (String) req.getAttribute( "javax.servlet.error.servlet_name"); writer.printf("servlet_name: %s%n", servletName); } }
JSP page for handling exception
<%@page contentType="text/html" pageEncoding="UTF-8" errorPage="true"%> <!doctype html> <html> <head> ... </head> <body> <ul> <li>Exception: ${requestScope['javax.servlet.error.exception']}</li> <li>Exception type: ${requestScope['javax.servlet.error.exception_type']}</li> <li>Exception message: ${requestScope['javax.servlet.error.message']}</li> <li>Request URI: ${requestScope['javax.servlet.error.request_uri']}</li> <li>Servlet name: ${requestScope['javax.servlet.error.servlet_name']}</li> <li>Status code: ${requestScope['javax.servlet.error.status_code']}</li> </ul> </body> </html>