Monday, November 18, 2024
Google search engine
HomeLanguagesJavaServlet – Exception Handling

Servlet – Exception Handling

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

Attributes

Description

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.

Syntax:

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

Example:

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

Exception-type related error pages

Syntax: 

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

Example:

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

Implementation:

Java




// Java Program to Illustrate ExceptionHandler
// Import required java libraries
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);
    }
}


File: web.xml

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>


Output: Run your ExceptionHandler.java code

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

RELATED ARTICLES

Most Popular

Recent Comments