❮ Previous Next ❯

JSP Exception Handling

Before going to JSP exception handling, first we have to understand what is an exception and how it is different from errors.

Exception:An unwanted or unexpected event that interrupts the normal flow of execution is known as exception. Exception is a disadvantageous fact. So we have to handle exceptions in order to graceful termination of the program.

Error:It can be a issue with the code or a system related issue which are irecoverable.

Exception_Handling

Exception Handling:

We can handle exceptions by using following two methods:

  1. Exception handling using exception implicit objects.
  2. Exception handling using try catch blocks within scriptlets.

Exception handling using exception implicit object

Consider the below example, here we have specified the exception handling page using errorPage attribute of page directive. If any exception occurs in the main JSP page the control will be transferred to the page mentioned in errorPage attribute. The handler page should have isErrorPage set to true in order to use. Thatís the reason we have set the isErrorPage true for errorpage.jsp.

Exception handling using exception implicit object

index.jsp

Example

<%@ page errorPage="errorpage.jsp" %>
<html>
<head>
<title>JSP exception handling</title>
</head>
<body>
<%
//Declared and initialized two integers
int number1 = 10;
int number2 = 0;
//It should throw Arithmetic Exception
int number3 = number1/number2;
%>
</body>
</html>

errorpage.jsp

Example

<%@ page isErrorPage="true" >
<html>
<head>
<title>Exception Message</title>
</head>
<body>
<h2>errorpage.jsp</h2>
<i>An exception has occurred in the index.jsp Page.
Please fix the errors. Below is the error message:</i>
<b><%= exception %></b>
</body>
</html>

Output

Exception handling using try catch blocks within scriptlets

We can handle the exception using try catch block also. Consider the below example. Here I have declared an array of length 5 and tried to access the 7th element which doesnít exist. It caused Array Index out of bounds exception.

index.jsp

Example

<html>
<head>
<title>JSP Exception handling using try catch block</title>
</head>
<body>
<%
try
{
int[] a={10,15,20,25,30};
int n=a[5];
out.println("6th element of array a is"+n);
}
catch (Exception exp)
{
out.println(exp);
}
%>
</body>
</html>

❮ Previous Next ❯


Follow Us




  Tutorials

Popular Links

Contact Us

address Plot No-N6/530,2ND Floor
Nayapalli,Jayadev Vihar
      Bhubaneswar-751015
      Email: info@silantechnology.com
      Phone: 0674-2361252
address
39877, sundale dr, apt#101, Fremont, California 94538, USA
       Phone: +1(262)388-7619

facebook twitter google linked in

© 2018 Silan Technology. All Rights Reserved