Catching Exceptions

If a particular type of problem frequently shows up in the log files, you may want to fine-tune the error handling and deal more gracefully with the problem. There’s a JSTL action named <c:catch>, described in Table 9-3, that can help you with this.

Table 9-3. Attributes for JSTL <c:catch>

Attribute name

Java type

Dynamic value accepted

Description

var
String

No

Optional. The name of the variable to hold the java.lang.Throwable if thrown by elements in the body.

Example 9-13 shows the top part of a modified version of the calc.jsp page that uses <c:catch> to catch divide-by-zero exceptions.

Example 9-13. Catching an exception (calc2.jsp)
<%@ page contentType="text/html" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page errorPage="errorpage.jsp?debug=log" %>
  
<html>
  <head>
    <title>Calculator</title>
  </head>
  <body bgcolor="white">
  
    <jsp:useBean id="calc" class="com.ora.jsp.beans.calc.CalcBean">
      <jsp:setProperty name="calc" property="*" />
    </jsp:useBean>
  
    <%-- Calculate the new numbers and state info --%>
    <c:catch var="error">
      <c:set var="currentNumber" value="${calc.currentNumber}" />
    </c:catch>
    <c:if test="${error != null}">
      <c:set var="currentNumber" value="Error" />
      <jsp:setProperty name="calc" property="reset" value="true" />
    </c:if>
    ...

The calc bean’s currentNumber property accessor method is the one that performs the calculation. By placing the <c:set> action with the EL expression that reads this property within the body of ...

Get JavaServer Pages, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.