Exception handling in JSP


JSP Action Tags :Previous                                                                        Next: Expression Language

Exception handling is a mechanism to handle run time errors, so that normal flow of the program can be maintained.

Ways of exception handling in JSP:

  1. 1. Using page directive (errorPage and isErrorPage attributes).
  2. 2. Using attribute of web.xml.

Exception handling example using errorPage and isErrorPage attributes:

welcome.jsp
<%@ page errorPage="errorPage.jsp" %>  
 
<html>
 <head>
   <title>isErrorPage and errorPage page directive example</title>
 </head>
 <body>
  <%= 0/0 %>
 </body>
</html>
errorPage.jsp
<%@ page isErrorPage="true" %>  
 
<html>
 <head>
   <title>isErrorPage and errorPage page directive example</title>
 </head>
 <body>
                <h3>Hello this is an isErrorPage and 
                    errorPage page directive example.</h3>
  <br/>
  <h3>Some exception occurred.</h3>
  Exception: <%=exception %>
 </body>
</html>
web.xml
<web-app>
 
  <welcome-file-list>
          <welcome-file>welcome.jsp</welcome-file>
  </welcome-file-list> 
 
</web-app>

Output:


Exception handling example using attribute:

welcome.jsp
<html>
 <head>
  <title>Exception handling example</title>
 </head>
 <body> 
  <% 
   out.print(10/0); 
  %>
 </body>
</html>
errorPage.jsp
<%@ page isErrorPage="true" %>
 
<html>
 <head>
  <title>error page</title>
 </head>
 <body> 
  Occurred exception is: <%= exception %>  
 </body>
</html>
web.xml
<web-app>
 
  <error-page>  
   <exception-type>java.lang.Exception</exception-type>  
   <location>/error.jsp</location>  
  </error-page> 
 
  <welcome-file-list>
    <welcome-file>welcome.jsp</welcome-file>
  </welcome-file-list>
</web-app>

Output:


JSP Action Tags :Previous                                                                        Next: Expression Language