How does JSP handle runtime exceptions?

You can use the errorPage attribute of the page directive. Any uncaught exceptions thrown in the body of the JSP page implementation class result in the forwarding of the client request and uncaught exception to the errorPage URL specified by the JSP page directive. For example:

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

redirects the browser to the JSP page error.jsp if an uncaught exception is encountered during request processing.

The offending java.lang.Throwable describing the error that occurred is stored in the javax.ServletRequest instance for the client request using the setAttribute() method, using the name javax.servlet.jsp.jspException. Names starting with the prefixes java and javax are reserved by the different specifications of the Java platform. The javax.servlet prefix is reserved and used by the Servlet and JSP specifications.

If the errorPage attribute of a page directive names a URL that refers to another JSP, and that target JSP page indicates that it is an error page (by setting the page directive's isErrorPage attribute to true) then the exception implicit scripting language variable of that page is initialized to the offending java.lang.Throwable reference.

Let's continuely with the above example. Within error.jsp, if you indicate that it is an error-processing page, via the directive:

<%@ page isErrorPage="true" %>

the Throwable object describing the exception may be accessed within the error page via the exception implicit object.

<%@ page isErrorPage="true" %>
<%= exception.getMessage() %>

With the following stack trace:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
exception.printStackTrace(new PrintStream(baos));


  • You must always use a relative URL as the value for the errorPage attribute in the page directive.
  • If autoFlush=true then if the contents of the initial Jsp- Writer has been flushed to the ServletResponse output stream then any subsequent attempt to dispatch an uncaught exception from the offending page to an errorPage may fail.
  • When an error page is also indicated in the web.xml descriptor, the JSP error page applies first, then the web.xml.

Printer-friendly version Printer-friendly version | Send this 
article to a friend Mail this to a friend

Previous Next vertical dots separating previous/next from contents/index/pdf Contents

  |   |