How to handle runtime exceptions in JSP?

Answered

How to handle runtime exceptions in JSP?

Ninja Asked on 18th September 2018 in Jsp.
Add Comment
1 Answer(s)
Best answer

In JSPs there are multiple ways to handle the exceptions :

  1. Using errorPage and isErrorPage attribute of page directive
  2. Using <error-page> element in the web.xml file
  3. Using Java Scriplets within a JSP file

Page Directive Attributes – errorPage and isErrorPage:

Any uncaught exceptions thrown in the body of the JSP page implementation class result in the forwarding of the client request and uncaught exception to the errorPage URL specified by the JSP page directive.

For example:

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

redirects the browser to the JSP page error.jsp if an uncaught exception is encountered during request processing. Within error.jsp, to indicate that it is an error-processing page, isErrorPage attribute must be set to true in the page directive:

<%@ page isErrorPage="true" %>

The Throwable object describing the exception may be accessed within the error page via the exception implicit object only if isErrorPage attribute is set to true.

<%@ page isErrorPage="true" %>
...
<%= exception.getMessage() %>

<error-page> element in the web.xml file:

This approach is better alternative as the user doesn’t need to use the page directive to declare the error page in each JSP file. Making a single entry in the web.xml file serves the purpose. We can either specify the exception type or the error code with the location element.

<error-page>
 <exception-type> java.lang.Exception </exception-type>
 <location> /error.jsp </location>
</error-page>

Java Scriptlet:

This approach is the traditional way of handling exceptions. This is not considered to be the best way of handling exception but used in case fast debugging is required. In this approach the developer can simply use the try … catch .. format within the scriptlet like any normal Java code.

Ninja Answered on 18th September 2018.
Add Comment