.


Divya

JSP Exception Handling with Example


Before going to start learn exception handling , let’s know what is exception.

Exception

Any unwanted or unexpected event that interrupts the normal flow of program execution is known as exception.

Generally Exception occurs when a user enter wrong data. It is a object that is thrown at run time.

Example :

Suppose we want to divide a number by zero in a Java application then it give a exception message that java.lang.AirthmeticException: / by zero

That means a number can’t be divide by Zero.

So to handle this type of problem exception handling process is used.

In JSP, there are two ways to perform exception handling:

  • By errorPage and isErrorPage attributes of page directive
  • By element in web.xml file

Exception Handling Example

exception.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>JSP Exception</title>
</head>
<body>
<%
try{
int array[]={1,2,3,4,5};
int number=array[6];
out.println("7th element of array"+number);
} catch (Exception exp){
out.println("<h3>The number you try to access is not available :</h3> <br>" + exp);
}
%>
</body>
</html>

Output

Exception

.