Tuesday 6 August 2013

How can we perform Exception Handling in JSP?

Exception handling can be performed in JSP with three ways
  1. Using page directive (isErrorPage=”True” and errorPage=”error.jsp”).
  2. Using simple Try/catch  
  3. Using JSTL

  1.  Page Directive Exception Handling: - This is the most common way of JSP exception handling. In this approach, we use the errorPage and isErrorPage methods of page directive. As in the below example, we used two JSP pages.
·         generateException.jsp
·         error.jsp
The generateException page used the errorPage method of page directive for describing the name of the page which will handle the exceptions occurred in the page (As error.jsp in below example). Now when any exception will occur in the generateException page, it will go to the error.jsp page.
              In error.jsp page we used the isErrorPage method of the page directive to tell the container that this page is for exception handling and then container will give an implicit object “Exception” for handling the exceptions. This can be easily understood with the below example.
generateException.jsp
<%@ page errorPage="error.jsp" %>
<%
  int count=0;
  count=100/count;

%>

error.jsp
<html>
<body>
<%@ page isErrorPage="true" %>
<%="Sorry, Exception occured"%>
</br>
<%="Here is your Exception:- "+exception%>
</body>
</html>


2.  Try/Catch Block exception handling: - This is very much similar to the core java exception handling. We put the code under the try block and catch the exception in exception block.
This can be easily understood with the example below.

generateException.jsp
<%
 try
  {
     int count=0;
     count=100/count;
  }
catch(Exception e)
  {
                out.println("Try/Catch block Exception Handling "+e);
  }

%>

3.       JSTL Exception: - JSTL (Java standard tag library) is used for making coding easy. JSTL gives some standard tags to perform some specific tasks so JSTL also provide tags to perform exception handling. Please refer the below example for JSTL exception handling.

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
 <body>
    <c:catch var="ExceptionVar">
    <% int count=0;
     count=100/count; %>
    </c:catch>
    Test :
                <c:if test = "${ExceptionVar != null}">
                out.println("Try/Catch block Exception Handling ");
                ${ExceptionVar}
    </c:if>
    </body>
</html>

No comments:

Post a Comment