JSP Tutorial - JSP Handle Exception








To handle exceptions with in the same page without using the error handling page, use try....catch block.

<html>
<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>

In JSP we can specify an Error Page for each JSP page to handle the exception. Whenever the page throws an exception, the JSP container automatically returns the error page.

The following code shows how to specifiy an error page for a main.jsp with the <%@ page errorPage="xxx" %> directive.

<%@ page errorPage="ShowError.jsp" %>
<html>
<body>
<%
   int x = 1;
   if (x == 1)
   {
      throw new RuntimeException("Error condition!!!");
   }
%>
</body>
</html>




Example

The following code is for ShowError.jsp which includes the directive <%@ page isErrorPage="true" %>. This directive generates the exception instance variable.

<%@ page isErrorPage="true" %>
<html>
<body>
<p>Here is the exception stack trace: </p>
<pre>
<% exception.printStackTrace(response.getWriter()); %>
</pre>
</body>
</html>




Example 2

The following code shows how to output exception information using JSP expression language.

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@page isErrorPage="true" %>
<html>
<body>
    <b>Error:</b>${pageContext.exception}
    <b>URI:</b>${pageContext.errorData.requestURI}
    <b>Status code:</b>${pageContext.errorData.statusCode}
    <c:forEach var="trace" items="${pageContext.exception.stackTrace}">
        <p>${trace}</p>
    </c:forEach>
</body>
</html>