The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > javax.servlet.jsp  [18 examples] > Java Server Pages Output  [4 examples]

e1060. Handling Unhandled Exceptions in a JSP Page

A JSP page should handle any exceptions that might arise from the use of scriptlets, expressions, or other JSP elements. However, there is always a chance that something unexpected happens and an unhandled exception is thrown. A JSP page can specify a specific page to be included when an unhandled exception is thrown. This error page would typically show an error message to the user, log the error message, and possibly notify an administrator of the problem.

Author's note: Some developers design their pages to throw an exception (e.g. NumberFormatException) if the user's input is invalid and then have the error page handle the exception. However, if an unhandled exception does arise, the error page can become confused. I prefer to handle input errors by explicitly checking for them and then including (see e1054 Including a File in a JSP Page) the appropriate error page if necessary.

A JSP page specifies the error page with the page directive and errorPage attribute. When an unhandled exception occurs, any unflushed output in the output stream is discarded and the error page is immediately executed. Here is an example of JSP page specifying erropage.jsp to be the error page:

    <%@ page errorPage="errorpage.jsp" %>
    
    <%
        if (request.getParameter("param").equals("value")) {
            // ...
        }
    
        // The test above will throw a NullPointerException if param is
        // not part of the query string. A better implementation would be:
        if ("value".equals(request.getParameter("param"))) {
            // ...
        }
    %>
The error page indicates that it is an error page with the page directive and isErrorPage attribute. This makes the unhandled exception available in a variable called exception. Here is an example of an error page that simply prints the name of the unhandled exception:
    <%@ page isErrorPage="true" %>
    
    An unexcepted error occurred. The name of the exception is:
    
    <%= exception %>

 Related Examples
e1057. Commenting a JSP Page
e1058. Generating Dynamic Content on a JSP Page
e1059. Implementing Conditional Content on a JSP Page

See also: Java Server Pages    Java Server Pages Headers    Java Server Pages Input   


© 2002 Addison-Wesley.