Exception Handling in JSP

An exception is problem that occurs during the execution of any program. Exception can be categorized as:

  • Runtime Exception – It is an exception that occurs during running (executing) the program.
  • Checked Exception – It is a user error in the code. It cannot be necessarily detected by testing.
  • Errors – This cannot be handled either at compile time or runtime. It’s problem beyond the control of the user.

Exception Object is an instance of class java.lang.Throwable. Following are methods in the java.lang.Throwable class:

public void printStackTrace()This method is used to print the http exception and its stack trace to the standard error stream.
public StackTraceElement[] getStackTraceThis method returns an array of stack elements, each represent one stack frame. The zeroth element of the array will be present at the top of the stack.
public String toString()This method returns the textual representation of String object.
public Throwable getCause()This method returns the cause of exception if the cause is unknown.
public String getMessage()This method returns the detail message about the exception.

We need to use the tag to make JSP page exception handler. In the following example we have link to an error page as errorpage.jsp to set the exception that occurs during execution of the program.

Listing 1: example.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1" errorPage="errorpage.jsp" import="java.util.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<% int a,b;

	out.print("a is less then b");
	throw new RuntimeException("Error condition!!!");


We have written an errorpage.jsp program. In which it include tag isErrorPage=”true”.

<%@ page language="java” pageEncoding="ISO-8859-1" import="java.util.*";
isErrorPage="true" %>

   <title>Error Handling</title>
<h1>Hey some error occurred !!!</h1>

<p>Your page generates an exception</p>
<% exception.printStackTrace(response.getWriter()); %>

Execute the JSP file example.jsp in Eclipse by selecting Run As > Run On Server and output would be as seen below:


Previous Tutorial : Cookies Handling in JSP

Leave a Reply

Your email address will not be published. Required fields are marked *

Pin It on Pinterest

Share This

Share this post with your friends!