Sobes.tech
Junior

How is error handling done with JSTL?

sobes.tech AI

Answer from AI

JSTL provides a set of tags for error handling in JSP pages.

Main mechanisms:

  1. <c:catch> tag: Allows catching exceptions that occur within its body.

    • The var attribute specifies the name of the variable in which the caught exception (of type java.lang.Throwable) will be stored.
    • If an exception occurs, the var variable will not be null.
    <%-- Example of using c:catch --%>
    <c:catch var="exception">
        <%-- Code that may cause an error --%>
        <% int divisionByZero = 10 / 0; %>
    </c:catch>
    
    <c:if test="${not empty exception}">
        <%-- Display error information --%>
        <p>An error occurred: ${exception.message}</p>
    </c:if>
    
  2. Error pages: You can configure a JSP page to handle specific exception types or all exceptions in general. This is achieved using the <error-page> element in the deployment descriptor web.xml:

    <!-- Example of error page configuration in web.xml -->
    <error-page>
        <exception-type>java.lang.Throwable</exception-type>
        <location>/errorPage.jsp</location>
    </error-page>
    
    <error-page>
        <error-code>404</error-code>
        <location>/notFound.jsp</location>
    </error-page>
    
    • On error pages, JSTL tags can be used (for example, to display exception information available through the exception variable).

Comparison table:

Mechanism Purpose Scope
<c:catch> Catch exceptions within JSP code Part of JSP page
Error pages Centralized exception and error code handling All JSP pages of the application

Combining these approaches allows for flexible and reliable error handling in Java web applications. <c:catch> is suitable for local handling of expected exceptions, while error pages are for global handling of unforeseen situations.

How is error handling done with JSTL? — Java - sobes.tech