Servlet - Exception Handling
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.
- 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.
- 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:
Similar Reads
Java Exception Handling Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc. An Exception is an unwanted or unexpected event that occurs during the execution of a program, i.e., at runt
10 min read
Exception handling in JSP Java Server Pages declares 9 implicit objects, the exception object being one of them. It is an object of java.lang.Throwable class, and is used to print exceptions. However, it can only be used in error pages. There are two ways of handling exceptions in JSP. They are:Â By errorPage and isErrorPage
3 min read
Spring MVC - Exception Handling Prerequisites: Spring MVC When something goes wrong with your application, the server displays an exception page defining the type of exception, the server-generated exception page is not user-friendly. Spring MVC provides exception handling for your web application to make sure you are sending your
6 min read
Exception Handling in Spring Boot Exception handling in Spring Boot helps deal with errors and exceptions present in APIs, delivering a robust enterprise application. This article covers various ways in which exceptions can be handled and how to return meaningful error responses to the client in a Spring Boot Project. Key Approaches
8 min read
Exception Handling in Programming Exception handling is a critical aspect of programming, enabling developers to manage unexpected or erroneous situations gracefully. In this article, we'll discuss the concept of exception handling, its importance, and best practices for implementing it effectively in various programming languages.
7 min read