The exception is normally an object that is thrown at runtime. Exception Handling is the process to handle the runtime errors. There may occur exception any time in your web application. So handling exceptions is a safer side for the web developer. 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 exception handling in jsp by the elements of page directive

In this case, you must define and create a page to handle the exceptions, as in the error.jsp page. The pages where may occur exception, define the errorPage attribute of page directive, as in the process.jsp page.

There are 3 files:

  • index.jsp for input values
  • process.jsp for dividing the two numbers and displaying the result
  • error.jsp for handling the exception





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


<%@ page isErrorPage="true" %>  

Sorry an exception occured!

Exception is: <%= exception %>

Output of this example:

exception handling in jsp exception handling in jsp exception handling in jsp exception handling in jsp