Exception Handling


JSP exception handling is the process of handling exceptional conditions that occurs in our webpage during run time.

In jsp, we can handle the exceptions in 2 ways:

  1. By using the errorPage and isErrorPage attributes of a page directive
  2. By using the <error-page> element in a xml file


Example: Handling error by errorPage and isErrorPage attributes

In the following example, we have created 2 jsp pages i.e. index.jsp and error.jsp. Whenever an exception occurs in the index.jsp page then the user is redirected to the error page i.e. error.jsp page to inform the user that an exception has occurred.

index.jsp

    <%@ page errorPage=”error.jsp” %>
    <html>
        <body>
            <%
                int a=7, b=0;
                int c = a/b;
                out.print(“Division of a/b is :” + c);
            %>
        </body>
    </html>


error.jsp

    <%@ page isErrorPage=”true” %>
    <h1>Sorry an exception occurred while dividing the numbers</h1>    



Example: Handling error by <error-page> attribute

In the following example, we have created 2 jsp pages and 1 xml page. Whenever an exception occurs in the index.jsp page then the user is redirected to the error page i.e. error.jsp page to inform the user that an exception has occurred and web.xml page will display the type of error.

index.jsp

    <%@ page errorPage=”error.jsp” %>
    <html>
        <body>
            <%
                int a=7, b=0;
                int c = a/b;
                out.print(“Division of a/b is :” + c);
            %>
        </body>
    </html>


error.jsp

    <%@ page isErrorPage=”true” %>
    <h1>Sorry an exception occurred while dividing the numbers</h1>    


web.xml

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