Easy Tutorial
❮ Jstl Function Escapexml Jstl Xml Param Tag ❯

JSP Exception Handling

When writing JSP programs, programmers may overlook some bugs, which can appear anywhere in the program. JSP code typically includes the following types of exceptions:

This section will provide several 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 on error pages. The following table lists some important methods in the Throwable class:

Number Method & Description
1 public String getMessage() Returns the exception message. This message is initialized in the Throwable constructor.
2 public Throwable getCause() Returns the cause of the exception, which is a Throwable object.
3 public String toString() Returns the class name.
4 public void printStackTrace() Prints 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 Throwable fillInStackTrace() Fills the Throwable object with the current stack trace.

JSP provides the option to specify an error page for each JSP page. Whenever an exception is thrown, the JSP container automatically calls 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()); %>
</pre>
</body>
</html>
❮ Jstl Function Escapexml Jstl Xml Param Tag ❯