JSP and Beyond

a pragmatic primer on building web-based solutions with Java technologies

When Things go Wrong - Error Handling

JSP has some very nice ways of dealing with error handling. I touched on this a bit in the “Anatomy of a JSP Application” when Implicit Objects were reviewed, but a directive can be set called “errorPage” for the JSP Page to indicate where to go when an error occurs. When an exception happens, the current page forwards an exception object to the page specified.

This subsequent page needs to have the Page directive “isErrorPage” set to true to receive the exception. It can then access all of the attributes of the exception, which is useful for sending in an email or display in a user friendly way.


<%@ page errorPage=”CatchError.jsp”%>

<!– Hmmm… what happens if we do this? –>
<% out.println((1/0)); %>


<%@ page isErrorPage=”true” %>

<!– Show how bad we did –>
<h1>Ouch! That hurt :(</h1>
Here is what was so bad : <b><%= exception.getMessage() %></b>

Notice that although we specified the CatchError.jsp to show the error, the end user will never see CatchError.jsp in the browser window. The error and output are all done under the covers and are not obvious to the user.

In reality you would probably want to do something more useful with the error, such as storing the error output in a utility bean that sends an email to a system administrator. As you can see, it is fairly straightforward to implement some gentle exception handling within JSP rather than showing an end user a very large, unfriendly stack trace.