IBM Skip to main content
Search for:   within 
      Search help  
     IBM home  |  Products & services  |  Support & downloads   |  My account

developerWorks > Java technology
developerWorks
EJB best practices: Build a better exception-handling framework
58KBe-mail it!
Contents:
Nested exceptions
A hierarchy of exceptions
Resources
About the author
Rate this article
Related content:
EJB best practices series
Subscriptions:
dW newsletters
dW Subscription
(CDs and downloads)
Deliver more useful exceptions without sacrificing clean code

Level: Intermediate

Brett McLaughlin (mailto:brett@oreilly.com?cc=&subject=Build a better exception-handling framework)
Author and Editor, O'Reilly and Associates
1 January 2003

Column iconEnterprise applications are often built with little attention given to exception handling, which can result in over-reliance on low-level exceptions such as java.rmi.RemoteException and javax.naming.NamingException. In this installment of EJB Best Practices, Brett McLaughlin explains why a little attention goes a long way when it comes to exception handling, and shows you two simple techniques that will set you on the path to building more robust and useful exception handling frameworks.

In previous tips in this series, exception handling has been peripheral to our core discussion. One thing you may have picked up, however, is that we've consistently distanced low-level exceptions from the Web tier. Rather than have the Web tier handle exceptions such as java.rmi.RemoteException or javax.naming.NamingException, we've supplied exceptions like ApplicationException and InvalidDataException to the client.

Remote and naming exceptions are system-level exceptions, whereas application and invalid-data exceptions are business-level exceptions, because they deliver more applicable business information. When determining what type of exception to throw, you should always first consider the tier that will handle the reported exception. The Web tier is generally driven by end users performing business tasks, so it's better equipped to handle business-level exceptions. In the EJB layer, however, you're performing system-level tasks such as working with JNDI or databases. While these tasks will eventually be incorporated into business logic, they're best represented by system-level exceptions like RemoteException.

Theoretically, you could have all of your Web tier methods expect and respond to a single application exception, as we did in some of our previous examples. But that approach wouldn't hold up over the long run. A far better exception-handling scheme would be to have your delegate methods throw more specific exceptions, which are ultimately more useful to the receiving client. In this tip, we'll discuss two techniques that will help you create more informative, less generalized exceptions, without generating a lot of unnecessary code.

Nested exceptions
The first thing to think about when designing a solid exception-handling scheme is the abstraction of what I call low-level or system-level exceptions. These are generally core Java exceptions that report errors in network traffic, problems with JNDI or RMI, or other technical problems in an application. RemoteException, EJBException, and NamingException are common examples of low-level exceptions in enterprise Java programming.

These exceptions are fairly meaningless, and can be especially confusing when received by a client in the Web tier. A client that invokes purchase() and receives back a NamingException has little to work with when it comes to resolving the exception. At the same time, your application code may need to access the information within these exceptions, so you can't simply throw out or ignore them.

The answer is to provide a more useful type of exception that also contains a lower-level exception. Listing 1 shows a simple ApplicationException that does just this:

Listing 1. A nested exception


package com.ibm;

import java.io.PrintStream;
import java.io.PrintWriter;

public class ApplicationException extends Exception {

       /** A wrapped Throwable */
       protected Throwable cause;

       public ApplicationException() {
           super("Error occurred in application.");
       }

       public ApplicationException(String message)  {
           super(message);
       }

       public ApplicationException(String message, Throwable cause)  {
           super(message);
           this.cause = cause;
       }

       // Created to match the JDK 1.4 Throwable method.
       public Throwable initCause(Throwable cause)  {
           this.cause = cause;
           return cause;
       }

       public String getMessage() {
           // Get this exception's message.
           String msg = super.getMessage();

           Throwable parent = this;
           Throwable child;

           // Look for nested exceptions.
           while((child = getNestedException(parent)) != null) {
               // Get the child's message.
               String msg2 = child.getMessage();

               // If we found a message for the child exception, 
               // we append it.
               if (msg2 != null) {
                   if (msg != null) {
                       msg += ": " + msg2;
                   } else {
                       msg = msg2;
                   }
               }

               // Any nested ApplicationException will append its own
               // children, so we need to break out of here.
               if (child instanceof ApplicationException) {
                   break;
               }
               parent = child;
           }

           // Return the completed message.
           return msg;
       }

       public void printStackTrace() {
           // Print the stack trace for this exception.
           super.printStackTrace();

           Throwable parent = this;
           Throwable child;

           // Print the stack trace for each nested exception.
           while((child = getNestedException(parent)) != null) {
               if (child != null) {
                   System.err.print("Caused by: ");
                   child.printStackTrace();

                   if (child instanceof ApplicationException) {
                       break;
                   }
                   parent = child;
               }
           }
       }

       public void printStackTrace(PrintStream s) {
           // Print the stack trace for this exception.
           super.printStackTrace(s);

           Throwable parent = this;
           Throwable child;

           // Print the stack trace for each nested exception.
           while((child = getNestedException(parent)) != null) {
               if (child != null) {
                   s.print("Caused by: ");
                   child.printStackTrace(s);

                   if (child instanceof ApplicationException) {
                       break;
                   }
                   parent = child;
               }
           }
       }

       public void printStackTrace(PrintWriter w) {
           // Print the stack trace for this exception.
           super.printStackTrace(w);

           Throwable parent = this;
           Throwable child;

           // Print the stack trace for each nested exception.
           while((child = getNestedException(parent)) != null) {
               if (child != null) {
                   w.print("Caused by: ");
                   child.printStackTrace(w);

                   if (child instanceof ApplicationException) {
                       break;
                   }
                   parent = child;
               }
           }
       }

       public Throwable getCause()  {
           return cause;
       }
}

The code in Listing 1 is fairly straightforward; we've simply chained together multiple exceptions to create a single, nested exception. The real benefit, however, is in using this technique as the starting point to create an application-specific hierarchy of exceptions. An exception hierarchy will let your EJB clients receive both business-specific exceptions and system-specific information, without requiring you to write a lot of extra code.

A hierarchy of exceptions
Your exception hierarchy should begin with something fairly robust and generic, like ApplicationException. If you make your top-level exception too specific you'll end up having to restructure your hierarchy later to fit in something more generic.

So, let's say that your application called for a NoSuchBookException, an InsufficientFundsException, and a SystemUnavailableException. Rather than create individual exceptions for each, you could set up each exception to extend ApplicationException, providing only the few additional constructors needed to create a formatted message. Listing 2 is an example of such an exception hierarchy:

Listing 2. An exception hierarchy


package com.ibm.library;

import com.ibm.ApplicationException;

public class NoSuchBookException extends ApplicationException {

       public NoSuchBookException(String bookName, String libraryName) {
      super("The book '" + bookName + "' was not found in the '" +
        libraryName + "' library.");
  }
}

The exception hierarchy makes things much simpler when it comes to writing numerous specialized exceptions. Adding a constructor or two for each exception class rarely takes more than a few minutes per exception. You will also often need to provide subclasses of these more specific exceptions (which are in turn subclasses of the main application exception), providing even more specific exceptions. For example, you might need an InvalidTitleException and a BackorderedException to extend NoSuchBookException.

Enterprise applications are often built with almost no attention given to exception handling. While it's easy -- and sometimes tempting -- to rely on low-level exceptions like RemoteException and NamingException, you'll get a lot more mileage out of your application if you start with a solid, well-thought-out exception model. Creating a nested, hierarchical exception framework will improve both your code's readability and its usability.

Resources

About the author
Brett McLaughlin has been working in computers since the Logo days (remember the little triangle?). He currently specializes in building application infrastructure using Java and Java-related technologies. He has spent the last several years implementing these infrastructures at Nextel Communications and Allegiance Telecom, Inc. Brett is one of the co-founders of the Java Apache project, Turbine, which builds a reusable component architecture for Web application development using Java servlets. He is also a contributor of the EJBoss project, an open source EJB application server, and Cocoon, an open source XML Web-publishing engine. Contact Brett at mailto:brett@oreilly.com?subject=Build a better exception-handling framework.


58KBe-mail it!

What do you think of this document?
Killer! (5) Good stuff (4) So-so; not bad (3) Needs work (2) Lame! (1)

Comments?



developerWorks > Java technology
developerWorks
  About IBM  |  Privacy  |  Terms of use  |  Contact