Introduction to Exception Handling in JSP
- Exception is an event that arises during the execution of the program. It terminates the program abnormally.
- Exception handling is the process of handling the abnormal termination of the program.
- Exception handling in JSP is easier than Java technology. JSP also uses same exception class object.
1. Using isErrorPage and errorPage attribute of page directive.
2. Using <error-page> tag in Deployment Descriptor.
Example : Exception handling using isErrorPage & errorPage attribute
//result.jsp
<%@ page errorPage="error.jsp" %>
<html>
<head>
<title>JSP Exception Handling</title>
</head>
<body>
<%
int a = 46;
int b = 0;
int result = a/b ;
%>
</body>
</html>
//error.jsp
<%@ page isErrorPage = "true" %>
<html>
<head>
<title>Exception Page</title>
</head>
<body>
<h3>Sorry an exception occured!</h3>
Exception is: <%= exception %>
</body>
</html>
Using try and catch Block
In JSP, we can also handle the exception by using try and catch block. It works on same page instead of firing an error page.Example : Using try & catch block in JSP page for exception handling
<html>
<head>
<title>Exception handling in JSP using try catch blocks</title>
</head>
<body>
<%
try
{
int arr[] = {9,8,7,6,5,4,3};
int num = arr[10];
out.println("11th element of arr"+num);
}
catch (Exception exp)
{
out.println("Cannot find the given index: " + exp);
}
%>
</body>
</html>


