JSP Exception Handling

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

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

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


Using the Exception Object

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

No. Method&Description
1 public String getMessage()Returns information about the exception. This information is initialized in the Throwable constructor.
2 public ThrowablegetCause()Returns the cause of the exception as a Throwable object.
3 public String toString()Returns the class name.
4 public void printStackTrace()Outputs the exception stack trace to System.err.
5 public StackTraceElement [] getStackTrace()Returns the exception stack trace as an array of stack trace elements.
6 public ThrowablefillInStackTrace()Fills in the Throwable object with the current stack trace.

JSP provides an option to specify an error page for each JSP page. Whenever a page throws an exception, the JSP container will automatically invoke the error page.

The following example specifies an error page for main.jsp. Use the <%@page errorPage="XXXXX"%> directive to specify an error page.

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

<html>
<head>
   <title>Error Handling Example</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()); %>