- Java EE Tutorials
- JSP Tutorials
- Recommended Books for Java Server Pages (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:
Code | Description |
public void printStackTrace() | This method is used to print the http exception and its stack trace to the standard error stream. |
public StackTraceElement[] getStackTrace | This 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"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Calculation</title> </head> <body> <% int a,b; a=6; b=4; if(a<=b) out.print("a is less then b"); else { throw new RuntimeException("Error condition!!!"); } %> </body> </html>
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" %> <html> <head> <title>Error Handling</title> </head> <body> <h1>Hey some error occurred !!!</h1> <p>Your page generates an exception</p> <% exception.printStackTrace(response.getWriter()); %> </body> </html>
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