JSP - SPLessons

Exception Handling in JSP

Chapter 17

SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Exception Handling in JSP

Exception Handling in JSP

shape Description

Exception Handling in JSP – When the programmer writes any JSP code, if any, error occurs in that code at run-time, the web container creates one of the implicit object “exception object”. The following error pages are displayed in JSP page.

  • Checked Exceptions: Checked exceptions are generated at the time of compilation which is typically the user exception or syntax error problem written by a programmer. For example, if try block is written, but forgot to write catch block or finally block it shows exception “please write catch block or finally block”.
  • Unchecked Exceptions:Unchecked exceptions are generated at runtime. These kind of exceptions are avoided by the programmer, These exceptions are not identified by JVM at the time of compilation.
  • Error: These errors are done mistakes in the code part and are rarely done by the programmers. One can ignore errors by changing the code. In JSP exception handling will be done in two ways as follows.

Methods to Handle Exceptions

shape Methods

Exceptions are handled using exception object and some of the methods of exception object are listed as below.

shape Example

This file should be in active mode while compiling .

<form action="process.jsp">  
	Enter number 1:<input type="text" name="n1" />
        Enter number 2:<input type="text" name="n2" />
        <input type="submit" value="divide"/>  

Where created two text fields to enter the values and created divide button to perform operation.


<%@ page errorPage="error.jsp" %>  
<% String num1=request.getParameter("n1"); String num2=request.getParameter("n2"); int a=Integer.parseInt(num1); int b=Integer.parseInt(num2); int c=a/b; out.print("division of numbers is: "+c); %>  

Where used request.getParameter() method to retrieve the input values.


//to handle the exception
<%@ page isErrorPage="true" %>  
<h3>Sorry an exception occured!</h3>
      Exception is: <%= exception %> 

If error occurred then it displays a message that is Sorry an exception occured!.

After executing the exception.jsp file , output will be as follows.Where enter the values to perform the divide operation.

After entered the values ,output will be as follows.


shape Key Points

  • Exception Handling in JSP – Developer can use JSTL tags also to write error message.
  • Exception Handling in JSP – public String getMessage() Returns a detailed message about the exception that has occurred.
  • Exception Handling in JSP – public String toString() Returns the name of the class concatenated with the result of getMessage()