Error handling

When a client request is processed, runtime errors can occur in the body of the implementation class for the JSP or in Java code that is called by the page. These exceptions can be handled in the code in the JSP using the Java language’s exception mechanism.

Uncaught exceptions

Any exceptions that are thrown from the body of the implementation class and are not caught can be handled using an error page that you specify using a page directive. Both the client request and the uncaught exception are forwarded to the error page. The java.lang.Throwable exception is stored in the javax.ServletRequest instance for the client request using the putAttribute method, using the name javax.servlet.jsp.jspException.

Using an error page JSP

If you specify a JSP as the error page, you can use its implicit exception variable to obtain information about the exception. The exception variable is of type java.lang.Throwable and is initialized to the Throwable reference when the uncaught exception is thrown.

To specify an error page for a JSP, set its errorPage attribute to the URL of the error page in a page directive:

<%@ page errorPage="ErrorPage.jsp" %>

To define a JSP as an error page, set its isErrorPage attribute to true in a page directive:

<%@ page isErrorPage="true" %>

This sample error page JSP uses the exception variable’s toString method to return the name of the actual class of this object and the result of the getMessage method for the object. If no message string was provided, toString returns only the name of the class.

The example also uses the getParameterNames and getAttributeNames methods of the request object to obtain information about the request.

<%@ page language="java" import="java.util.*"
	isErrorPage="true" %>
<H1 align="Center">Exceptions</H1>
<br><%= exception.toString() %>
<%! Enumeration parmNames; %>
<%! Enumeration attrNames; %>
<br>Parameters:
<%	parmNames = request.getParameterNames();
	while (parmNames.hasMoreElements()) {
%>
	<br><%= parmNames.nextElement().toString() %>
<%
	}
%>
<br>Attributes:
<%	attrNames = request.getAttributeNames();
	while (attrNames.hasMoreElements()) {
%>
		<br><%= attrNames.nextElement().toString() %>
<%
	}
%>