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:
Checked Exceptions: Checked exceptions are typical user errors or errors 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: Runtime exceptions may have been avoided by the programmer and will be ignored at compile time.
Errors: Errors are not exceptions, but they are beyond the control of users or programmers. Errors are usually ignored in the code; there is little you can do about them. For example, a stack overflow error. These errors are 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 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>