8 exception对象
如果在Jsp页面中出现没有捕获的异常,就会生成exception对象,并把它传送到在page指令中设定的错误页面中,然后在错误处理页面中处理相应的exception对象。exception对象只有在错误处理页面(在页面指令里isErrorPage=true)才可以使用。
exception对象常用方法如下表所示:
方法名称 | 说明 |
---|---|
getMessage() | 获取异常消息字符串 |
toString() | 以字符串形式返回对异常的描述 |
实例代码:
<%@ page language="java" pageEncoding="GB2312" errorPage="third_example8_error.jsp"%>
<html>
<body>
<%!int a=8;%>
<%=a/0%>
</body>
</html>
错误处理页面:
<%@ page language="java" pageEncoding="GBK" isErrorPage="true"%>
<html>
<body>
<H2>
<font color="red">
错误原因:
<%=exception.getMessage()%>
<%=exception.toString()%>
</font>
</H2>
</body>
</html>
程序说明:
errorPage=“error.jsp” 指定错误处理页面。
isErrorPage=“true” 指定该页面是错误处理页面。
在错误处理页面<%=exception.getMessage() %>输出获取的异常消息字符串。
运行结果:
注意:如果用内置浏览器有可能出不来,最好用谷歌浏览器。