Internet Programming with Java Course

Exception Handling in JSP Pages
by Faisal Khan.

Overview
In this article we will learn how exceptional events can occur in a JSP page and how to catch these exceptional events to display a more useful message to the user.

What are Exceptions ?
Exceptions mean exceptional events and as we all know exceptional events can occur anywhere in a program e.g. you are trying to connect to a database and the database server is down, now you wouldn't have expected this to happen ;).

How to catch Exceptions ?
You can catch exceptions in a JSP page like you would do in other Java classes. Simply put the code which can throw an exception/s between a try..catch block.

<%
try {
       // Code which can throw can exception
} catch(Exception e) {
       // Exception handler code here
}
%>

There is yet another useful way of catching exceptions in JSP pages. You can specify error page in the 'page' directive. Then if any exception is thrown, the control will be transferred to that error page where you can display a useful message to the user about what happened and also inform your sysadmin about this exception depending obviously on how important it may be.

In this article we will explore this error page method of exception handling in JSP pages.

Building Demo Pages
To demonstrate the run-time exception handling feature of JSP pages, we will build three pages.

i. Form.html
Create a new Form.html page. Copy the following code and paste it into the Form.html page :

<html>
<head>
       <style>
       body, input { font-family:Tahoma; font-size:8pt; }
       </style>
</head>
<body>
 
<!-- HTML Form -->
<form action="FormHandler.jsp" method="post">
       Enter your age ( in years ) : 
       <input type="text" name="age" /> 
       <input type="submit" value="Submit" />
</form>
 
</body>
</html>

Explanation
Form.html page simply displays a single input field Form to the user to enter his age in years. The name of input field where user will enter his/her age is "age". We will use this input field name "age" in the FormHandler.jsp page to receive it's value.

ii. FormHandler.jsp
Create new FormHandler.jsp page. Copy and paste the following code in it :

<%@ page errorPage="ExceptionHandler.jsp" %>
<html>
<head>
       <style>
       body, p { font-family:Tahoma; font-size:10pt; }
       </style>
</head>
<body>
 
<%-- Form Handler Code --%>
<%
       int age;
       age = Integer.parseInt(request.getParameter("age"));
%>
 
<%-- Displaying User Age --%>
<p>Your age is : <%= age %> years.</p>
 
<p><a href="Form.html">Back</a>.</p>
 
</body>
</html>

Explanation
Code above is rather simple. Notice the first line, the page directive. It specifies an errorPage ExceptionHandler.jsp, our exception handler JSP page.

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

Then we declare an int variable "age". Then using the static method of Integer class we parse the entered value using Integer.parseInt() method. The value is retrieved using request.getParameter() method. The argument to request.getParameter() is the name of Form field whose value we want to retrieve.

<%
       int age;
       age = Integer.parseInt(request.getParameter("age"));
%>

If all goes well and user entered an int ( e.g. 12345 ) value in the input field then we display that value back to the user.

<p>Your age is : <%= age %> years.</p>

Now things can go wrong and exceptional events can occur. For example, if user didn't enter a value and what if user entered his name ( e.g. "Faisal Khan"), of String type instead of an integer ?.

These things will be handled by the ExceptionHandler.jsp JSP page.

iii. ExceptionHandler.jsp
Create a new ExceptionHandler.jsp page. Copy and paste the following code in it :

<%@ page isErrorPage="true" import="java.io.*" %>
<html>
<head>
       <title>Exceptional Even Occurred!</title>
       <style>
       body, p { font-family:Tahoma; font-size:10pt; padding-left:30; }
       pre { font-size:8pt; }
       </style>
</head>
<body>
 
<%-- Exception Handler --%>
<font color="red">
<%= exception.toString() %><br>
</font>
 
<%
out.println("<!--");
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
exception.printStackTrace(pw);
out.print(sw);
sw.close();
pw.close();
out.println("-->");
%>
 
</body>
</html>

Explanation
To make a JSP page exception handler ( i.e. errorPage ), you have to specify isErrorPage attribute in the page directive at the top and set it's value to true.

<%@ page isErrorPage="true" %>

When a JSP page has been declared an errorPage, it is made available an object with name of "exception" of type java.lang.Throwable. We use different methods of this exception object to display useful information to the user.

<font color="red">
       <%= exception.toString() %><br>
</font>

We can put the stack trace information for debugging inside HTML <!-- --> comment tags. So that user only sees a useful message and the sysadmin, developers can see the whole story.

<%
out.println("<!--");
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
exception.printStackTrace(pw);
out.print(sw);
sw.close();
pw.close();
out.println("-->");
%>

To use the PrintWriter and StringWriter classes you'll have to import java.io.* package in your JSP page by changing the page directive at the top to :

<%@ page isErrorPage="true" import="java.io.*" %>

Running the Demo Pages
Place Form.html, FormHandler.jsp and ExceptionHandler.jsp pages in a place where your application server ( e.g. Tomcat, Orion etc ) can find them. Never put your JSP pages in the /WEB-INF/ folder.

I placed these three pages in the /web/jsp/ folder so the path to these pages on my system will be http://localhost:8080/web/jsp/Form.html and so on. Notice that on my system application server is running on 8080 port. You should change the port number to the one where your application server is running.

Enter your age e.g. 24, in the input field and press the submit button. You should see FormHandler.jsp page giving you a response like following :

Your age is : 24 years.

Now try again. This time don't enter any value or simply enter a non-integer value e.g. your name, and press the submit button. Now instead of FormHandler.jsp page showing you your age, the control will be internally passed to ExceptionHandler.jsp page which will show an exception message in red color :

java.lang.NumberFormatException:

To see the complete stack trace view the source of the page. On Internet Explorer, click View -> Source. On the source page you will see complete exception stack trace written.