Skip to content
Related Articles

Related Articles

Servlet – Exception Handling

View Discussion
Improve Article
Save Article
  • Last Updated : 16 Feb, 2022

When a servlet throws an exception, the web container looks for a match with the thrown exception type in web.xml configurations that employ the exception-type element. To define the invocation of servlets in response to particular errors or HTTP status codes, you’d have to utilize the error-page element in web.xml.

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

  1. Programmatically exception handling technique: This method of managing exceptions in Java programming by using try and catch blocks are known as a programmatic exception handling mechanism.
  2. A mechanism for managing declarative exceptions: Declarative exception handling technique refers to the method of managing exceptions using XML elements in the web.xml file. If an error occurs in more than one servlet application, this method is handy.

 Important Points

  • If the web application throws a ServletException or an IOException, the web container calls the /ErrorHandler servlet.
  • Different Error Handlers can be defined to handle different sorts of errors or exceptions.
  • The ErrorHandler servlet is specified in the web.xml file and is defined in the same way as any other servlet.
  • If an error with the status code 404INot Found) or 403 is encountered, the ErrorHandler servlet is invoked (Forbidden)

Request Attributes – Errors/Exception



status_code  Returns a status code that may be saved and studied after being saved in java.lang variable.
exception_type Provides information about the exception type that may be kept and studied after being saved in java.lang file. 
message Provides information about the actual error message that may be saved and studied after being saved in java.lang file
request_uri Provides information about the URL used to call the servlet and may be kept and studied after being stored in java.lang variable. 
exception Provides information about the raised exception, which may be preserved and investigated.
servlet_name Returns a list of servlet names that may be saved and studied after being saved in java.lang file. The data type is a string.

Configuration of web.xml

Error-code-related error pages can be configured in the web.xml file.


< error - page >
< error - code > code < / error - code >
<location> / url < / location >
< / error - page >


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

Exception-type related error pages


< error - page >
< exception - type > exception type < / exception - type >
<location> / url < / location >
< / error - page >


< error - page >
< exception - type > javax.servlet.ServletException < / exception - type >
<location> / ErrorHandler < / location >
< / error - page >



// Java Program to Illustrate ExceptionHandler
// Import required java libraries
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(
        Integer statusCode = (Integer)request.getAttribute(
        String servletName = (String)request.getAttribute(
        if (servletName == null) {
            servletName = "Unknown";
        String requestUri = (String)request.getAttribute(
        if (requestUri == null) {
            requestUri = "Unknown";
        // Set response content type
        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) {
                "<h1>Error information not found</h1>");
            out.println("Let's go back to <a href=\""
                        + response.encodeURL(
                        + "\">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());
    // Method
    // To handle POST method request.
    public void doPost(HttpServletRequest request,
                       HttpServletResponse response)
        throws ServletException, IOException
        doGet(request, response);

File: web.xml


 <!-- servlet mappings -->

Output: Run your code

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

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!