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:
-
<c:catch>tag: Allows catching exceptions that occur within its body.- The
varattribute specifies the name of the variable in which the caught exception (of typejava.lang.Throwable) will be stored. - If an exception occurs, the
varvariable will not benull.
<%-- 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> - The
-
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 descriptorweb.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
exceptionvariable).
- On error pages, JSTL tags can be used (for example, to display exception information available through the
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.