<c:catch> JSTL tag is used in exception handling. Earlier we shared how to do exception handling in JSP – the two ways. In this post we are gonna discuss exception handling using <c:catch> core tag.
Syntax:
<c:catch var ="variable_name"> //Set of statements in which exception can occur </c:catch>
variable_name can be any variable in which exception message would be stored. If there is an exception occurs in the statements enclosed in <c:catch> then this variable contains the exception message. Let’s understand this with the help of an example.
Example
In this example we are intentionally throwing arithmetic exception by dividing an integer with zero and then we are printing the errormsg variable (which contains the exception message) using Expression language (EL).
Note: If there is no exception in the block of statements in <c:catch> then the variable (in example it’s errormsg) should have null value. That’s the reason we are checking errormsg!=null before printing the variable’s value.
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <html> <head> <title>JSTL c:catch Core Tag Example</title> </head> <body> <%! int num1=10; int num2=0; %> <c:catch var ="errormsg"> <% int res = num1/num2; out.println(res);%> </c:catch> <c:if test = "${errormsg != null}"> <p>There has been an exception raised in the above arithmetic operation. Please fix the error. Exception is: ${errormsg}</p> </c:if> </body> </html>
Output