<c:catch> JSTL 标签用于异常处理。之前我们分享了如何在 JSP 中进行异常处理 - 两种方式。在这篇文章中,我们将使用<c:catch>核心标签讨论异常处理。
语法:
<c:catch var ="variable_name">//Set of statements in which exception can occur</c:catch>
variable_name可以是存储异常消息的任何变量。如果<c:catch>中包含的语句中发生异常那么这个变量包含异常消息。让我们借助一个例子来理解这一点。
例
在这个例子中,我们故意通过将整数除以零来抛出算术异常,然后我们使用表达式语言(EL)打印errormsg变量(包含异常消息)。
注:如果<c:catch>中的语句块中没有异常那么变量(例如它的errormsg)应该具有空值。这就是我们在打印变量值之前检查errormsg != null的原因。
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %><html><head><title>JSTL c:catch Core Tag Example</title></head><body><%!int num1=10;int num2=0; %><c:catch var ="errormsg"><% int res = num1/num2;out.println(res);%></c:catch><c:if test = "${errormsg != null}"><p>There has been an exception raised in the abovearithmetic operation. Please fix the error.Exception is: ${errormsg}</p></c:if></body></html>
输出:

