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 page, using the Java language’s exception mechanism.

Uncaught exceptions

Exceptions that are thrown from the body of the implementation class that are not caught can be handled using an error page. You specify the error page 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, with the name javax.servlet.jsp.jspException.

Using an error page JSP

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

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:

<%@ page isErrorPage="true" %>

This sample error page uses the exception object’s toString method to return the name of the class of the object causing the exception 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() %>
<%
   }
%>