JSTL Core <c:catch> Tag
The JSTL Core <c:catch> tag is used in exception handling to handle errors that occur during runtime by catching any Throwable object(an exception) in its body.
Attributes of <c:catch> Tag
The <c:catch> tag has a single optional attribute:
- var: The name of the page-scoped variable to store the exception in. If this attribute is not specified, the exception will not be stored in any variable.
Example of <c:catch> Tag
The following example shows how to use the <c:catch> tag to detect an arithmetic error of divide-by-zero as an exception:
HTML
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> < html > < head > < title >JSTL Core < c:catch > Tag Example</ title > </ head > < body > < c:catch var = "catchtheException" > <% int x = 2 / 0; %> </ c:catch > < c:if test = "${catchtheException != null}" > < p >An exception occurred: ${catchtheException.message}</ p > </ c:if > </ body > </ html > |
In this code, we divide a number by zero, which is not possible in mathematics thus resulting in an error. The <c:catch> tag will catch this exception and store it in the variable catch the exception. The <c:if> tag will then check if the variable is null. If it is not null, then the exception message will be displayed to the user.
Note: Since division by zero(0) is not possible in Mathematics, it can be thrown as error.
Usage of <c:catch> Tag
There can be many use cases for <c:catch> tag. Some of them are listed below:
- Can also be used in log generation into a file/database.
- You can also use this tag to detect an error and redirect the user to an error page.
- It can also be used to provide the user with an option to retry.
The <c:catch> tag is overall a great tool for handling exceptions in JSP pages. It can help you to create more robust and user-friendly applications.
Contact Us