JSP Exception Handling

JSP Exception Handling with Examples

In this article, I am going to discuss JSP Exception Handling with Examples. Please read our previous article where we discussed Debugging in JSP Applications with Examples. As part of this article, we are going to discuss the following pointers.

  1. What is JSP Exception?
  2. Exception Handling in JSP
  3. Checked exceptions and Runtime exceptions
  4. Methods of handling exceptions:
  5. Exception handling using exception implicit object
  6. Exception handling using try-catch blocks within scriptlets
  7. Using JSTL tags for Error Page
  8. JSP Error Page
  9. JSP Error Page Configuration
  10. Error Page Deployment Descriptor Configuration
  11. Example of exception handling in JSP by the elements of page directive
  12. Example of exception handling in JSP by specifying the error-page element in web.xml file
  13. Catching exceptions directly on the JSP page
  14. Page-level exception handling
  15. Application-level exception handling
What is JSP Exception?

Exceptions are the run time errors that occur during the execution of the program. It is an unexpected event that interrupts the normal flow of the program which is throws at runtime. When an exception occurs, program execution gets terminated.

What is Exception Handling?

While executing the program there is a chance of occurring errors in the application which are called exceptions. Whenever an exception occurs then the program will be terminated in the middle of the execution of the program, which is called abnormal termination or incomplete execution. To resolve this problem, we have to use exception handling.

Exception Handling is the process of handling the statements or skipping the statements which may generate exceptions and providing an alternative solution, continue with the rest of the program and close / terminate the program normally.

Types of Exceptions

We have the following two types of Exceptions:

  1. Checked Exceptions
  2. Unchecked Exceptions
Checked Exceptions

Exceptions that identified at compilation time and occurred at runtime are called checked exceptions. It is also called Compile Time Exceptions. An exception said to be checked exception whose exception handling is mandatory as per the compiler. Examples: IOException, ClassNotFoundException, CloneNotSupportedException, etc.

Unchecked Exceptions

Exceptions that identified and occurred at run-time are called Unchecked Exceptions. It is also called Runtime Exceptions. An exception is said to be an unchecked exception whose exception handling is optional as per the compiler. Examples: Arithmetic Exception, NumberFormatException, NoSuchMethodError, etc.

Note: All child classes of Error and Runtime Exception classes are called unchecked exceptions and remaining classes are called checked exceptions.

What is an Error?

An Error is a serious problem that a reasonable application should not try to catch. We have the following two types of errors:

  1. Compile Time Error
  2. Run Time Error
Compile Time Error

Errors that occur at the time of compilation of the program are called compile-time errors. Compile-time errors occurred because if we don’t follow the java syntaxes properly, java programming rules properly, etc. Compile-time errors are identified by the java compiler.

Run Time Error

Errors that occur at the time of execution of the program are called runtime errors. It is also called Exceptions. The exceptions may occur because programmer logic fails or JVM fails. Exceptions are identified by JVM. The process of handling these run-time errors or exceptions is called Exception Handling.

Exception Handling Methods

Following are the methods used for Exception Handling:

  1. getMessage(): It gives a detailed description of the exception that has occurred.
  2. getCause(): It gives the cause of the exception.
  3. toString(): It gives the name of the class concatenated with the result of getMessage().
  4. printStackTrace(): It gives the result of the toString() along with the stack trace to System error which is the error output stream.
  5. getstackTrace(): It gives the array of all the elements of the stack trace.
  6. fillInStackTrace(): It is used to fill the Throwable object with a recent stack trace with any previous information.
Ways to handle JSP Exceptions

Using try-catch block/ catching exception directly on JSP page. We can use a try-catch block to handle exceptions in JSP. Let us understand the use of try-catch black with an example.

tryCatch.jsp

In this example, we will try to parse a number through a URL query string. If you will input a number you will get an appropriate message otherwise you will get an error message.

<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Exception Handling using Try Catch</title>
</head>
<body>
 <%
 try {
  int y = Integer.parseInt(request.getParameter("y"));
 %>
 <h3>
  The number is y=:
  <%=y%></h3>
 <%
 } catch (NumberFormatException x) {
 %>
 <h3>
  Number Format Exception <br /> Error: y must be a number
 </h3>
 <%
 }
 %>
</body>
</html>
Output

If you will pass the appropriate number in the URL, you will get the following output:

Ways to handle JSP Exceptions

If you will pass any other value in the URL, you will get the following output:

JSP Exception Handling with Examples

Advantage: It is one of the easiest ways to implement a try-catch block and is suitable for specific and recoverable errors in case the exception occurs.

Disadvantage: As the JSP page is used to represent the view layer so it is not a good practice to use Java code directly into JSP pages. If we want to handle exceptions for more than one JSP page then we need to duplicate try-catch blocks in every JSP page which is not an efficient approach.

Page-level Exception Handling / Handling exception using page directives in JSP

In page-level exception handling, we are using page directives to specify separate error pages. If an exception occurs in the JSP page it will redirect you to a separate error page. There are following two elements of Page Directives used for handling exceptions:

  1. errorPage: It is a separate error page we can write to handle exceptions which are showing exception class name, error message, and exception stack trace. If our main JSP page throws an exception it will redirect you to the specified error handling page.
  2. isErrorPage=”true”: It is an error handling page thrown by the main JSP page when an error occurs so the server will pass the exception object thrown by the original JSP page which is a subclass of java.lang.Throwable class. The error handler page must have the isErrorPage attribute to be set to “true” to use an exception implicit object.
Example

In this example Calculate.jsp is the main JSP page which calculates the division of two numbers passed from query URL string and error.jsp is the error handling jsp page for handling errors.

Calculate.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
 errorPage="error_jstl.jsp" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Calculate division of two numbers</title>
</head>
<body>
 <%
 int x = Integer.parseInt(request.getParameter("x"));
 int y = Integer.parseInt(request.getParameter("y"));

 int div = x / y;
 %>
 <h2>
  Division of
  <%=x%>
  and
  <%=y%>
  is
  <%=div%></h2>
</body>
</html>
error.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
 isErrorPage="true" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Error Page</title>
</head>
<body>
 <h2>
  Error:
  <%=exception.getClass().getName()%><br />
  <%=exception.getMessage()%><br />
 </h2>
</body>
</html>
Output

Input two number values using the URL query string, you will get the following output:

Page-level Exception Handling / Handling exception using page directives in JSP

If you will enter the denominator as zero then an exception will occur which will redirect you to the error.jsp page and you will get the following output:

JSP Exception Handling with Examples

Using JSTL tags for the error page in JSP Application

We can use JSTL on the error page instead of accessing the object using the JSP scriptlet. Use the following error.jsp page in the above code:

error.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@page isErrorPage="true"%>
<html>
<head>
<title>Error Page</title>
</head>
<body>
 <table width="100%" border="1">
  <tr valign="top">
   <td width="40%"><b>Error:</b></td>
   <td>${pageContext.exception}</td>
  </tr>

  <tr valign="top">
   <td><b>URI:</b></td>
   <td>${pageContext.errorData.requestURI}</td>
  </tr>

  <tr valign="top">
   <td><b>Status code:</b></td>
   <td>${pageContext.errorData.statusCode}</td>
  </tr>

  <tr valign="top">
   <td><b>Stack trace:</b></td>
   <td><c:forEach var="trace"
     items="${pageContext.exception.stackTrace}">
     <p>${trace}</p>
    </c:forEach></td>
  </tr>
 </table>

</body>
</html>
Output

Now run calculate.jsp page by providing numbers in the query URL string, you will get the following output:

Using JSTL tags for the error page in JSP Application

If you will provide zero as a value in the denominator, you will get the following output:

Using JSTL tags for the error page in JSP Application

Advantages: In this approach, we can create a separate error handling page and re-use it in more than one JSP page which is more convenient than try-catch blocks.

Disadvantages: In this approach, we cannot specify an error page per exception type because we have only one error handling page for all types of exceptions. So, we have to specify the attribute errorPage of the page directives whenever we are adding new JSP pages. Also, whenever we are changing the file, we need to update all the JSP pages as well.

Application-Level Exception Handling (specifying error page in web.xml file) in JSP Application

In this approach, we can configure error handling pages by adding some entries in the web.xml file. Whenever an exception occurs on the main JSP page it will tell the server to redirect the clients to the error.jsp page which does not have to declare the attribute isErrorPage.

Syntax for error page configuration is:

<error-page>
    <exception-type>fully_qualified_name_of_exception_class</exception-type>
    <location>path_to_error_jsp_page</location>
</error-page>

Example

For this example, in this example Calculate.jsp is the main JSP page which calculates the division of two numbers passed from query URL string and we are specifying the specific entry in the web.xml file which will handle the exception. Here, we can specify the exception type or the error code(if known) with the location element. In case, you want to handle all the exceptions specify the java.lang.Exception in the exception-type element.

Calculate.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
 errorPage="error.jsp" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Calculate division of two numbers</title>
</head>
<body>
 <%
 int x = Integer.parseInt(request.getParameter("x"));
 int y = Integer.parseInt(request.getParameter("y"));

 int div = x / y;
 %>
 <h2>
  Division of
  <%=x%>
  and
  <%=y%>
  is
  <%=div%></h2>
</body>
</html>
error.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@page isErrorPage="true"%>
<html>
<head>
<title>Error Page</title>
</head>
<body>
 <h1>Exception caught</h1>  
The exception is: <%= exception %>

</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
  http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">

<welcome-file-list> 
   <welcome-file>Calculate.jsp</welcome-file>
</welcome-file-list>
<error-page>  
  <exception-type>java.lang.Exception</exception-type>  
  <location>/error.jsp</location>  
  </error-page> 
</web-app>
Output

Now run calculate.jsp page by providing numbers in the query URL string, you will get the following output:

Application-Level Exception Handling (specifying error page in web.xml file) in JSP Application

If you will provide zero as a value in the denominator, you will get the following output:

JSP Exception Handling with Examples

In the next article, I am going to discuss Expression Language in JSP. Here, in this article, I try to explain JSP Exception Handling with Examples and I hope you enjoy this JSP Exception Handling with Examples article.

Leave a Reply

Your email address will not be published.