Exception handling can be performed in JSP with three ways
- Using page directive (isErrorPage=”True” and errorPage=”error.jsp”).
- Using simple Try/catch
- Using JSTL
- 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>
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);
}
%>
<%@
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