Servlet - Exception Handling

Last Updated : 16 May, 2026

Servlet Exception Handling is used to manage runtime errors and display meaningful error messages instead of server-generated error pages. When an exception occurs, the web container checks the web.xml file and forwards the request to the configured error handler servlet or page.

  • Exception handling improves application reliability and user experience.
  • Errors can be handled using HTTP status codes or exception types.
  • Custom error pages can be configured using the <error-page> element in web.xml.

Exception Handling is the process of transforming system error messages into user-friendly error messages.

Types of Exception Handling in Servlet

1. Programmatic Exception Handling

Exceptions are managed directly inside Java code using Java exception handling keywords like try, catch, throw, throws, and finally. It helps developers handle runtime errors and prevent abnormal program termination.

  • Provides better control over exception handling logic.
  • Useful for handling specific exceptions at the code level.

Syntax:

try {
// risky code
}
catch(Exception e) {
// exception handling code
}
finally {
// cleanup code
}

2. Declarative Exception Handling

Exceptions are managed using XML configuration in the web.xml file instead of writing handling code inside servlets. The web container automatically redirects the request to a configured error page or servlet when an exception occurs.

  • Centralizes exception handling for multiple servlets.
  • Makes the application cleaner and easier to maintain.

Syntax:

<error-page>
<exception-type>java.lang.Exception</exception-type>
<location>/ErrorHandler</location>
</error-page>

Request Attributes Available During Exception Handling

Attributes

Description

status_code Stores the HTTP status code
exception_type

Stores the type of exception

message

Stores the actual error message

request_uri

Stores the requested URL

exception

Stores the exception object

servlet_name

Stores the servlet name

Configuring Error Pages in web.xml

The web.xml file allows developers to configure custom error pages for specific HTTP status codes or exceptions. When an error occurs, the web container automatically forwards the request to the configured error handling servlet or page.

  • Used for handling HTTP status code errors.
  • Improves user experience with custom error pages.

There are two ways to configure error pages in web.xml.

1. Error Code Based Configuration

This configuration is used to handle HTTP status code errors such as 404, 403, or 500.

Syntax:

<error-page>
<error-code>404</error-code>
<location>/ErrorHandler</location>
</error-page>

Explanation: In this configuration, if a 404 Not Found error occurs, the web container redirects the request to the ErrorHandler servlet. This helps display a custom and user-friendly error page instead of the default server error page.

2. Exception Type Based Configuration

This configuration is used to handle specific Java exceptions thrown by servlets or JSP pages. The web container checks the exception type and forwards the request to the configured error handler.

Syntax: 

<error-page>
<exception-type>java.lang.Exception</exception-type>
<location>/ErrorHandler</location>
</error-page>

Explanation: In this configuration, if any java.lang.Exception occurs in the application, the request is redirected to the ErrorHandler servlet. This allows centralized handling of exceptions and displays meaningful error information to the user.

Custom Exception Handling Using ExceptionHandler in Servlet

This example demonstrates how a servlet-based web application handles errors using a centralized ExceptionHandler servlet. It captures both HTTP errors (like 404) and Java exceptions using web.xml configuration and displays a user-friendly error page instead of the default server error.

Step 1: Create Servlet Class

we create a class named ExceptionHandler.java which extends HttpServlet and is used to handle application errors. This servlet manages 404 errors, runtime exceptions, and missing pages by displaying a custom error page instead of the default server error.

Java
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

// Extend HttpServlet class
public class ExceptionHandler extends HttpServlet {

    // Method
    // To handle GET method request
    public void doGet(HttpServletRequest request,
                      HttpServletResponse response)
        throws ServletException, IOException
    {

        // Analyze the servlet exception
        Throwable throwable
            = (Throwable)request.getAttribute(
                "javax.servlet.error.exception");
        Integer statusCode = (Integer)request.getAttribute(
            "javax.servlet.error.status_code");
        String servletName = (String)request.getAttribute(
            "javax.servlet.error.servlet_name");

        if (servletName == null) {
            servletName = "Unknown";
        }
        String requestUri = (String)request.getAttribute(
            "javax.servlet.error.request_uri");

        if (requestUri == null) {
            requestUri = "Unknown";
        }

        // Set response content type
        response.setContentType("text/html");

        PrintWriter out = response.getWriter();
        String title = "Error/Exception Information";
        String docType
            = "<!doctype html public \"-//w3c//dtd html 4.0 "
              + "transitional//en\">\n";

        out.println(docType + "<html>\n"
                    + "<head><title>" + title
                    + "</title></head>\n"
                    + "<body bgcolor = \"#f0f0f0\">\n");

        if (throwable == null && statusCode == null) {
            out.println(
                "<h1>Error information not found</h1>");
            out.println("Let's go back to <a href=\""
                        + response.encodeURL(
                            "http://localhost:8080/")
                        + "\">Home Page</a>.");
        }
        else if (statusCode != null) {
            out.println("The status code of an error is : "
                        + statusCode);
        }
        else {
            out.println("<h2>Error information</h2>");
            out.println("Servlet Name : " + servletName
                        + "</br></br>");
            out.println("Exception Type : "
                        + throwable.getClass().getName()
                        + "</br></br>");
            out.println("The request URI: " + requestUri
                        + "<br><br>");
            out.println("The exception message: "
                        + throwable.getMessage());
        }
        out.println("</body>");
        out.println("</html>");
    }

    // Method
    // To handle POST method request.
    public void doPost(HttpServletRequest request,
                       HttpServletResponse response)
        throws ServletException, IOException
    {

        doGet(request, response);
    }
}

Step 2: Configure web.xml

we configure the ExceptionHandler servlet and map it to a specific URL pattern so it can handle requests. We also define error-page mappings for 404 errors and all exceptions, so whenever an error occurs, the request is redirected to the ExceptionHandler servlet to display a custom error page.

XML
<web-app>
 <servlet>
  <servlet-name>ExceptionHandler</servlet-name>
  <servlet-class>ExceptionHandler</servlet-class>
 </servlet>
 <!-- servlet mappings -->
 <servlet-mapping>
  <servlet-name>ExceptionHandler</servlet-name>
  <url-pattern>/ExceptionHandler</url-pattern>
 </servlet-mapping>
 <error-page>
  <error-code>404</error-code>
  <location>/ExceptionHandler</location>
 </error-page>
 <error-page>
  <exception-type>java.lang.Throwable</exception-type>
  <location>/ExceptionHandler</location>
 </error-page>
</web-app>

Step 3: Run the Project

  • Right click your project -> Run on server
  • Open browser:

http://localhost:8080/ExceptionHandlerDemo/ExceptionHandler

Output:

Run your ExceptionHandler.java code

Now try entering some different URLs, the expected output will be the following:

Comment