Open In App

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:



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:




<%@ 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:

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.

Article Tags :