JSP program for error handling

Q. Explain error handling in JSP with example.

Answer:

Below example describe the exception handling concept in JSP page. The exception class works same as simple java program. There are 3 files in this example index.html, process.html, error.jsp.

index.html

<html>
    <head>
        <title>Exception Example</title>
    </head>
    <body>
        <form action="process.jsp">  
            <fieldset style="width:20%; background-color:#e6ffe6;">
                <center>
                    <h3>Exception Example</h3>
                    Enter number: <input type="text" name="n1" /><br/><br/>  
                    Enter number: <input type="text" name="n2" /><br/><br/>  
                    <input type="submit" value="Divide"/>  
                </center>
            </fieldset>
        </form>  
    </body>
</html>


process.jsp

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


error.jsp

<%@ page isErrorPage="true" %>  
  
<h3>Sorry an exception occured!</h3>  
  
Exception is: <%= exception %>


web.xml

<web-app>
    <servlet>
        <servlet-name>xyz</servlet-name>
        <jsp-file>/index.jsp</jsp-file>
    </servlet>
    <servlet-mapping>
        <servlet-name>xyz</servlet-name>
        <url-pattern>/test</url-pattern>
    </servlet-mapping>
</web-app>


Output:

exception

Click the "Divide" button.

Division of numbers is: 5

When we enter valid number for division it gives proper output.

However, if we enter invalid number or leave any box blank, it gives error message.

exception

Click the "Divide" button.

error message