JSTL c:catch with c:if

If you have written some code which you think that it can invoke a error, and still you are confident that you can recover from that solution by yourself.

JSTL c:catch with c:if

JSTL c:catch with c:if

        

If you have written some code which you think that it can invoke a error, and still you are confident that you can recover from that solution by yourself. Then then is one tag provided to you that is <c:catch> which is one of the tag of core action library. It works like a try/catch block in java. 

If we have any doubt that the particular code can invoke a error then we should write those codes inside the <c:catch> core action tag. The beauty of this tag is that it works both like a try and catch. There is no such thing like try tag. This tag can handle both the try and catch situation. 

By performing simple mathematical calculation we are going to teach how can we handle the exception by using the <c: if> tag. In this example firstly we have use one function random of class java.lang.Math inside the scriptlet directive. Now set the attribute by using the pageContext implicit object. Now in the jstl <c:out> core action tag use the attribute value to retrieve the value of the random number which we have set in the scriptlet. Now use the tag <c:if> to check the condition. In this example we have put the condition that if the value of the random number is less than 10 then it will show and exception otherwise no exception. For this we are also using <c:choose> tag. 

The code of the program is given below:

<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core"%>

<%
Double db= (Double) (Math.random() * 20);
pageContext.setAttribute("random", db, PageContext.PAGE_SCOPE);
%>

<html>
<head>
<title>Catching Exception by using c:if</title>
</head>
<body>
It will show the random number generated over which the decide whether the exception has been occured or not. <br> The number is : 
<c:out value = "${random}"/><br><br>
<c:if test="${pageScope.random < 10}">
<c:set var="randomFailed" value="true"/>
</c:if>

<c:choose>
<c:when test="${pageScope.randomFailed == true}">
Exception occurs at. ${random}
</c:when>
<c:otherwise>
No Exception at . ${random}
</c:otherwise>
</c:choose>
</body>
</html>

The output of the program is given below:

Download this example.