当编写JSP程序的时候,程序员可能会遗漏一些BUG,这些BUG可能会出现在程序的任何地方。JSP代码中通常有以下几类异常:
本节将会给出几个简单而优雅的方式来处理运行时异常和错误。
exception对象是Throwable子类的一个实例,只在错误页面中可用。下表列出了Throwable类中一些重要的方法:
序号 | 方法&描述 |
---|---|
1 | public String getMessage() 返回异常的信息。这个信息在Throwable构造函数中被初始化 |
2 | public ThrowablegetCause() 返回引起异常的原因,类型为Throwable对象 |
3 | public String toString() 返回类名 |
4 | public void printStackTrace() 将异常栈轨迹输出至System.err |
5 | public StackTraceElement [] getStackTrace() 以栈轨迹元素数组的形式返回异常栈轨迹 |
6 | public ThrowablefillInStackTrace() 使用当前栈轨迹填充Throwable对象 |
JSP提供了可选项来为每个JSP页面指定错误页面。无论何时页面抛出了异常,JSP容器都会自动地调用错误页面。
接下来的例子为main.jsp指定了一个错误页面。使用<%@page errorPage="XXXXX"%>指令指定一个错误页面。
- <%@ page errorPage="ShowError.jsp" %>
- <html>
- <head>
- <title>Error Handling Example</title>
- </head>
- <body>
- <%
- // Throw an exception to invoke the error page
- int x = 1;
- if (x == 1)
- {
- throw new RuntimeException("Error condition!!!");
- }
- %>
- </body>
- </html>
现在,编写ShowError.jsp文件如下:
- <%@ page isErrorPage="true" %>
- <html>
- <head>
- <title>Show Error Page</title>
- </head>
- <body>
- <h1>Opps...</h1>
- <p>Sorry, an error occurred.</p>
- <p>Here is the exception stack trace: </p>
- <pre>
- <% exception.printStackTrace(response.getWriter()); %>