Catching Exception using c: catch and c:set

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.

Catching Exception using c: catch and c:set

Catching Exception using c: catch and c:set

        

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. 

In this tag we are defining the attribute of the <c:catch> core action tag that is var. This attribute is optional and is used when we want to access the exception after the end of the <c:catch> tag.  In the example we have used another tag that is <c:set> which we used to set the attribute variables. The attribute var is a must in the tag <c:set>. For output we have used the <c:out> tag in which the attribute value is a must. The <c:if> tag is used in the example to check the condition.

The code of the program is given below:

 

<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<html>
<head>
<title>Catch an Exception</title>
</head>

<body>
<c:catch var="catchException">
<c:set var="x" value="5.0"/>

<c:set var="y" value="five"/>

We are trying to divide double x to String y. The result is well known.<br> 
<c:out value="${x*y}" />

<br />
</c:catch>

<c:if test = "${catchException!=null}">
There is an exception : ${catchException.message}<br>
</c:if>
</body>
</html>

The output of the program is given below:

Download this example.