This post helps you understand and use the <c:catch> tag in JSL core tags library.

You know, the <c:catch> tag allows us to catch any exceptions occurs in its body.

 

JSTL <c:catch> Syntax

<c:catch var="<string>">

...

</c:catch>

Attributes:

Name

Required

Type

Description

var

False

java.lang.String

Name of the variable for the thrown exception object. The type of this variable is of type of the exception being thrown.

Any JSP page can specify the error page in case any errors are thrown. The following snippet will redirect to the error page when any exception occurs during the execution of the JSP code.

<@ page errorPage=’/jsp/errors/myErrorpage.jsp’%>

The error page myErrorPage.jsp needs to specify that it is an error page in order to get access to the implicit object exception that references the exception thrown by the original JSP page.

<@ page isErrorPage="true" %>

This mechanism is good enough for handling exceptions in most situations; however it is more flexible if we can handle exceptions in the same page where those exceptions are thrown. The tag <c:catch> let us do exactly this. The following is an example on the usage of this tag.

<c:catch var="myWebSiteAccessException">
     <c:import url="http://www.codejava-not-found.net/"/>
 </c:catch>
<c:if test="${not empty myWebSiteAccessException}">
    Website not accessible!
    <c:out value="${myWebSiteAccessException.message}"/>
</c:if>

In the above example the <c:catch> catches the exception thrown by <c:import> in case the provided URL is not accessible, and stores the exception in a page-scoped variable named ‘myWebSiteAccessException’.

The <c:catch> tag has an optional attribute –var which specifies the name of the page-scoped variable to store the exception. We can then access this variable from the page scope in the same page the exception is thrown.

 

Output:

 catch-demo

The above screen captures shows us the exception when trying to access a website which is not found.

 

Recommended Usage of JSTL <c:catch>:

The <c:catch> is particularly useful to handle exceptions in the same page. We can use this tag if we are confident that any exception can be recovered in the same page or we can provide alternate functionality in the same page if the exception occurs.

 

Other JSTL Core Tags:

if |  choose   |  forEach  |  forTokens   |  import   |  out   |  param  |  redirect  |  remove   |  set  |  url


About the Author:

is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.



Add comment