Exception Handling in Servlet

As of now, we have discussed Filter in Servlet. In this article, we will discuss an Exception in Servlet. As we know, Exception is an event that happens during the execution of a program, therefore these need to be handled in the program. So, In this article, we will discuss How Exception is handled in Servlet.

What is Exception in Servlet?

Servlet provides support for Exception that is configured in the web.xml file of the application. The whole purpose of these is to handle the Exception and send a useful response to the user. Following is the web.xml file configuration for Exception Handling.

<!--Servlet-->
<servlet>
  <servlet-name>ErrorHandle</servlet-name>
  <servlet-class>ErrorHandle</servlet-class>
<servlet> 
<servlet-mapping>
  <servlet-name>ErrorHandle</servlet-name>
  <url-pattern>/ErrorHandle</url-pattern>
</servlet-mapping>
<!--Error code-->
<error-page>
  <error-code>403</error-code>
  <location>/ErrorHandle</location>
</error-page>
<!--Exception type--->
<error-page>
  <exception-type>javax.servlet.ServletException</exception-type>
  <location>/ErrorHandle</location>
</error-page>

For generic Exception, We should define the following error-page instead of defining separate error-page elements.

<error-page>
<exception-type>java.lang.Throwable</exception-type>
<location>ErrorHandle</location>
</error-page>

Request Attributes for Exception

  • javax.servlet.error.status_code:This attribute gives us the status code.
  • javax.servlet.error.exception_type:This attribute gives us the type of exception that occurred. As in the above web.xml file, the ServletException type is used.
  • javax.servlet.error.message:This attribute gives us the exact error message.
  • javax.servlet.error.request_uri:This attribute gives us the information on the URL calling the servlet.
  • javax.servlet.error.exception:This attribute gives us the information of Exception raised.
  • javax.servlet.error.servlet_name:This attribute gives us the servlet-name.

Let’s see the Example for Exception Handling in Servlet

In this example first, we will create a single servlet and web.xml file that will give you an understanding of attributes in Exception Handling.

Demo.java

Web.xml

Output

In this, if you type the wrong URL. You will get the following output which means we have handled the Error 404 page.