If a block could throw an exception, and we know how to recover to the possible error condition, we can shield that code using a c:catch JSTL tag. The name is a bit misleading, because it acts more like a "try" in the try/catch construct.
Let's see it at work:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!-- ... --> About to do a risky thing... <c:catch> <% int x = 10/0; %> </c:catch> <p>If you see this, we survived.</p>The Java scriptlet throws an exception, but this doesn't lead us to the error page, since the code is shielded by a c:catch.
If we want to keep track of the thrown exception we have to declare it as var attribute in the c:catch tag, and check it against null after the end of the c:catch block:
<c:catch var="ex"> Another risky thing ... <% int x = 10/0; %> <p> ... this line won't be printed</p> </c:catch> <c:if test="${ex != null}"> <br />Exception caught: ${ex.message} </c:if>The c:catch behave like a Java "try" block even in the sense that the code after the exception-generating line is not executed.
More on JSTL and error conditions in chapter nine of Head First Servlet and JSP.
No comments:
Post a Comment