Exception Handling in JSP

Exception Handling is a process of handling exceptional condition that might occur in your application. Exception Handling in JSP is much easier than Java Technology exception handling. Although JSP Technology also uses the same exception class object.In JSP, there are two ways to perform exception handling:

  1. By errorPage and isErrorPage attributes of page directive
  2. By error-page element in web.xml file

Example of isErrorPage and errorPage attribute:

We can handle the exceptions in jsp by specifying errorPage in the page directive,


				 <%@ page errorPage = "errorPage.jsp">

If any exception will be thrown then the control to handle the exception will be passed to that error page where we can display a information to the user about what's the reason behind throwing the exception.

Handling exceptions using error-page element in the 'web.xml'

This approach is better as the user doesn't need to use the page directive to declare the error page in each jsp file. Making a single entry in the web.xml file serves the purpose. We can either specify the exception type or the error code with the location element. If we want to handle all the exceptions we need to specify the java.lang.Exception in the exception type element. The web.xml file for each of these cases is given as under.

Downloads

1) web.xml file if you want to handle any exception:

		 
<web-app>

 <error-page>
  <exception-type>java.lang.Exception</exception-type>
  <location>/error.jsp</location>
  </error-page>
 
</web-app>

This approach is better if you want to handle any exception. If you know any specific error code and you want to handle that exception, specify the error-code element instead of exception-type as given below

2) web.xml file if you want to handle the exception for a specific error code

	
<web-app>

 <error-page>
  <error-code>500</error-code>
  <location>/error.jsp</location>
  </error-page>
 
</web-app>

2. index.jsp file is same as in the above example

3. process.jsp

Now, you don't need to specify the errorPage attribute of page directive in the jsp page.


<%@ 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);

%>