Skip to main content

EJB best practices: Build a better exception-handling framework

Deliver more useful exceptions without sacrificing clean code

Brett McLaughlin (brett@newInstance.com), Author and Editor, O'Reilly Media Inc.
Photo of Brett McLaughlin
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 brett@oreilly.com.

Summary:  Enterprise 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.

View more content in this series

Date:  01 Jan 2003
Level:  Intermediate
Activity:  3267 views

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

Photo of Brett McLaughlin

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 brett@oreilly.com.

Comments (Undergoing maintenance)



Trademarks  |  My developerWorks terms and conditions

Help: Update or add to My dW interests

What's this?

This little timesaver lets you update your My developerWorks profile with just one click! The general subject of this content (AIX and UNIX, Information Management, Lotus, Rational, Tivoli, WebSphere, Java, Linux, Open source, SOA and Web services, Web development, or XML) will be added to the interests section of your profile, if it's not there already. You only need to be logged in to My developerWorks.

And what's the point of adding your interests to your profile? That's how you find other users with the same interests as yours, and see what they're reading and contributing to the community. Your interests also help us recommend relevant developerWorks content to you.

View your My developerWorks profile

Return from help

Help: Remove from My dW interests

What's this?

Removing this interest does not alter your profile, but rather removes this piece of content from a list of all content for which you've indicated interest. In a future enhancement to My developerWorks, you'll be able to see a record of that content.

View your My developerWorks profile

Return from help

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Java technology
ArticleID=10746
ArticleTitle=EJB best practices: Build a better exception-handling framework
publish-date=01012003
author1-email=brett@newInstance.com
author1-email-cc=

My developerWorks community

Tags

Help
Use the search field to find all types of content in My developerWorks with that tag.

Use the slider bar to see more or fewer tags.

Popular tags shows the top tags for this particular content zone (for example, Java technology, Linux, WebSphere).

My tags shows your tags for this particular content zone (for example, Java technology, Linux, WebSphere).

Use the search field to find all types of content in My developerWorks with that tag. Popular tags shows the top tags for this particular content zone (for example, Java technology, Linux, WebSphere). My tags shows your tags for this particular content zone (for example, Java technology, Linux, WebSphere).

Rate a product. Write a review.

Special offers