2 Minutes To Code (β Version)

JSP - 2 minute tutorial

Jsp Exception : How to handle exceptions in webpage gracefully

Jsp specification provides for a graceful way of handling exceptions. It works like this :

First, you declare that a given jsp page (say typical.jsp) can possibly throw exception by using the page directive errorPage="errorHandlingPage.jsp". The jsp errorHandlingPage.jsp will actually handle the exception.

Then in errorHandlingPage.jsp, you use the page directive isErrorPage="true". Now whenever typical.jsp throws an exception outside try-catch block, the webserver invokes errorHandlingPage.jsp with an implicit object exception which is a reference to the exception thrown.

Let's see this in action below where typical.jsp tries to divide by zero in line no. 8.

Souce code of typical.jsp

<%@ page errorPage="errorHandlingPage.jsp" %>
		Let's divide 5 by 0.
			int divisor = 0;
			int dividend = 5;
			int result = dividend/divisor;
		The result is <%=result %>

Souce code of errorHandlingPage.jsp

<%@ page isErrorPage="true" %>
		An unexpected exception was encountered.
		The admin monkeys are looking into the issue.
		Exception is : <%= exception %>
Now when you deploy typical.jsp and errorHandlingPage.jsp and then point your browser to typical.jsp, the webpage shown below is produced.

There are other powerful ways to handle exceptions however. You can configure in the deployment descriptor(web.xml), the webpage to be displayed for different http status codes and also for different exception classes.