English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

JSP Exception Handling

When writing JSP programs, programmers may miss some bugs, which may appear anywhere in the program. There are usually the following types of exceptions in JSP code:

  • Checked exception: A checked exception is a typical user error or an error that a programmer cannot foresee. For example, if a file is about to be opened but the file cannot be found, an exception is thrown. These exceptions cannot be simply ignored at compile time.
  • Runtime exception: A runtime exception may have been avoided by the programmer, and this exception will be ignored at compile time.
  • Error: An error is not an exception, but the problem is that it goes beyond the control range of users or programmers. Errors are usually ignored in the code, and you can almost do nothing about them. For example, stack overflow errors. These errors will be ignored at compile time.

This section will provide several simple and elegant ways to handle runtime exceptions and errors.

Using the Exception object

The exception object is an example of a Throwable subclass and is only available in the error page. The following table lists some important methods in the Throwable class:

Number Method&Description
1 public String getMessage()

Return the message of the exception. This information is initialized in the Throwable constructor
2 public Throwable getCause()

Return the cause of the exception, which is a Throwable object
3 public String toString()

Return the class name
4 public void printStackTrace()

Output the exception stack trace to System.err
5 public StackTraceElement[] getStackTrace()

Return the exception stack trace in the form of an array of stack trace elements
6 public Throwable fillInStackTrace()

Use the current stack trace to fill the Throwable object

JSP provides an option to specify an error page for each JSP page. Whenever an exception is thrown on a page, the JSP container will automatically call the error page.

The following example specifies an error page for main.jsp. An error page is specified using the <%@page errorPage="XXXXX"%> directive.

<%@ page errorPage="ShowError.jsp" %>
<html>
<head>
   <title>Error Handling Example</title>/title>
</head>
<body>
<%
   // Throw an exception to invoke the error page
   int x = 1;
   if (x == 1)
   {
      throw new RuntimeException("Error condition!!!");
   }
%>
</body>
</html>

Now, write the ShowError.jsp file as follows:

<%@ page isErrorPage="true" %>
<html>
<head>
<title>Show Error Page</title>
</head>
<body>
<h1>Opps...</h1>
<p>Sorry, an error occurred.</p>
<p>Here is the exception stack trace: </p>
<pre>
<% exception.printStackTrace(response.getWriter()); %>

Note that the ShowError.jsp file uses the <%@page isErrorPage="true"%> directive, which tells the JSP compiler to generate an exception example variable.

Now try to access the main.jsp page, it will produce the following result:

java.lang.RuntimeException: Error condition!!!
......
Opps...
Sorry, an error occurred.
Here is the exception stack trace:

Using JSTL tags in the error page

You can use JSTL tags to write the error page ShowError.jsp. The code in this example is almost the same as the previous example, but it has a better structure and provides more information:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@page isErrorPage="true" %>
<html>
<head>
<title>Show Error Page</title>
</head>
<body>
<h1>Opps...</h1>
<table width="100%" border="1">
<tr valign="top">
<td width="40%"><b>Error:</b></td>
<td>${pageContext.exception}</td>
</tr>
<tr valign="top">
<td><b>URI:</b></td>
<td>${pageContext.errorData.requestURI}</td>
</tr>
<tr valign="top">
<td><b>Status code:</b></td>
<td>${pageContext.errorData.statusCode}</td>
</tr>
<tr valign="top">
<td><b>Stack trace:</b></td>
<td>
<c:forEach var="trace" 
         items="${pageContext.exception.stackTrace}">
<p>${trace}</p>
</c:forEach>
</td>
</tr>
</table>
</body>
</html>

The running result is as follows:

Using try…catch blocks

If you want to handle exceptions on a page and treat different exceptions differently, then you need to use try…catch blocks.

The following example shows how to use try…catch blocks, place these codes in main.jsp:

<html>
<head>
   <title>Try...Catch Example</title>
</head>
<body>
<%
   try{
      int i = 1;
      i = i / 0;
      out.println("The answer is ") + i);
   }
   catch (Exception e){
      out.println("An exception occurred: ") + e.getMessage());
   }
%>
</body>
</html>

Try to access main.jsp, it will produce the following result:

An exception occurred: / by zero