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>

Our Services:

Java Training | Python Training | Machine Learning with Python Training | Deep Learning with Python Training | Projects

SILAN Technology
Call to: 9439202111  |  9658317757  |  0674-2361252

Comment