Exception Handling in JSP

  1. By Using Error Page
  2. By Using PageContext
  3. By Using Try…Catch Block
  4. Specifying default error page in the web.xml

Using Error Page
To set up an error page, use the <%@ page errorPage="xxx" %> directive

<%@ page errorPage="ShowError.jsp" %>
<html>
<head>
   <title>Error Handling Example</title>
</head>
<body>
<%
   // Throw an exception to invoke the error page
   int x = 1;
   if (x == 1)
   {
      throw new RuntimeException("Error condition!!!");
   }
%>
</body>
</html>

Error-handling page includes the directive <%@ page isErrorPage="true" %>. This directive causes the JSP compiler to generate the exception instance variable.

<%@ page isErrorPage="true" %>
<html>
<head>
<title>Show Error Page</title>
</head>
<body>
<h1>Opps...</h1>
<p>Sorry, an error occurred.</p>
<p>Here is the exception stack trace: </p>
<pre>
<% exception.printStackTrace(response.getWriter()); %>
</pre>
</body>
</html>

Using JSTL tags in PageContext

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@page isErrorPage="true" %>
<table width="100%" border="1">
<tr valign="top">
<td width="40%"><b>Error:</b></td>
<td>${pageContext.exception}</td>
</tr>
<tr valign="top">
<td><b>URI:</b></td>
<td>${pageContext.errorData.requestURI}</td>
</tr>
</table>

Using Try Catch Block:

<html>
<head>
   <title>Try...Catch Example</title>
</head>
<body>
<%
   try{
      int i = 1;
      i = i / 0;
      out.println("The answer is " + i);
   }
   catch (Exception e){
      out.println("An exception occurred: " + e.getMessage());
   }
%>
</body>
</html>

Specifying default error page in the web.xml
web.xml

<error-page>
   <error-code>404</error-code>
   <location>/error404.html</location>
</error-page>

Sample.jsp

<%@ page errorPage="error.jsp" %>  
<%  
   String s=null;
   s.length();
%>

error.jsp

<%@ page isErrorPage="true" %>
<%= exception.getMessage() %>
Posted in JSP.

Comments are closed.