Exception handling in JSP

Exception handling is a mechanism to handle runtime 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 <error-page> 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:

jsp example 11
 
Download this example.

Exception handling example using <error-page> 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 example 26
 
Download this example.
 
Next Topic: jsp:useBean, jsp:setProperty and jsp:getProperty action tag.
Previous Topic: jsp:param action tag with example.

Related Topics:

JSP action tags with example.
jsp:forward action tag with example.
jsp:include action tag with example.
jsp:param action tag with example.
jsp:useBean, jsp:setProperty and jsp:getProperty action tag.
Exception handling in JSP with example.
JSP Expression Language with example.