JSTL Core Tag c:catch Example
- Details
- Written by Nam Ha Minh
- Last Updated on 31 August 2019   |   Print Email
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. |
<@ 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:
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
Comments