Welcome!

Java Authors: Elizabeth White, Liz McMillan, Carmen Gonzalez, Esmeralda Swartz, Pat Romanski

Related Topics: Java

Java: Article

Exception Chaining Simplifies Debugging

Exception Chaining Simplifies Debugging

Exception chaining (also known as "nesting exceptions"), is a technique for handling exceptions. A list is built of all the exceptions thrown as a result of a single originating exception as it's converted from lower to higher levels of abstraction. It can be used in both client and server environments to greatly simplify software debugging without adding undue complexity. This article discusses good exception-handling techniques and shows how to implement and use exception chaining.

Exceptions Are Part of the Interface
When our professors taught us about encapsulation and modular programming, we were told that modules should hide the details of their implementation. For example, an employee lookup service shouldn't advertise how or where it finds employees; only the methods required to access this service should be publicly available. This reduces complexity by isolating the implementation of one component from others that use it.

Most programmers realize that exceptions form an important part of the interface of any class, but aren't sure what to do with low-level exceptions that can't be handled directly by their code. Throwing a low-level exception from a higher-level class isn't a good idea because it exposes details of that class's implementation. The correct solution is for the class to catch the low-level exceptions, and to rethrow exceptions of a higher level of abstraction. If the getEmployee() method retrieves employee objects from a database via JDBC, for instance, a SQLException might be caught inside the method. This exception would be converted to an EmployeeLookupException and rethrown to the calling method.

Converting an Exception Object
There's no way, of course, to simply change the type of an exception. While it might be argued that we're converting from a more to a less specific exception, we can't cast one to the other because they don't have a parentÐchild relationship. For example, SQLException certainly doesn't extend from EmployeeLookupException or vice versa.

In this article "converting" an exception means to catch one exception type and throw a brand new exception of a different class. It's a conversion in the sense that the new exception is a direct result of the earlier one. When the EmployeeLookupException is created and thrown, it doesn't mean that a second error has occurred; it's just new packaging to represent the original error at a higher level of abstraction.

try {
stmt.execute(sql);
} catch (SQLException ex) {
throw new
EmployeeLookupException();
}

It quickly becomes obvious to many programmers that exception conversion (without chaining) has a serious deficiency: the root cause of the exception is lost. Is the EmployeeLookupException a result of a logon failure or a SQL query error? Exception conversion can make debugging more difficult.

I've argued in the paragraphs above that details of an implementation should be hidden from the user of the method, but we don't want to make debugging more difficult than necessary. The distinction to be made is that the internal implementation details should be hidden from the public API used at compile time, but this isn't a reason to obscure the cause and location of internal exceptions at runtime. We want to make these easy to discern. Correct exception handling with exception chaining achieves both these goals.

Upcasting and Other Poor Exception- Handling Techniques
One common solution to the problem of losing information with exception conversion is to convert through upcasting (i.e., casting "up" the tree to a superclass). Usually, the up-cast is to Exception and is programmed in an implicit manner by simply declaring that each method throws Exception. This undermines the intent of requiring exceptions to be caught in Java. The compiler doesn't require the programmer to catch any exceptions by this method.

public Employee getEmployee()
throws Exception
{
... database query code ...
}

While proper exception conversion adds context, making it more specific to the problem at hand, upcasting makes it more difficult to determine how to handle the exceptions. The desired exception conversions are from lower to higher levels of abstraction. This rarely matches the inheritance hierarchy of exceptions (which changes in amount of detail rather than abstraction - a very subtle difference). Remember that the abstraction a programmer seeks in designing a class should relate to the problem area he or she is trying to solve. For example, Exception is more generic than SQLException (a subclass of Exception), but it's probably not a higher level of abstraction for an employee lookup service. EmployeeLookupException and NoPermissionException are good examples of a higher level of abstraction in this case.

An even worse strategy for exception handling is to catch and log each exception (or not) before ignoring it. As long as the exception is logged, debugging is relatively straightforward. Unfortunately, this leaves no way for the calling method to detect or handle the error, which again eliminates the value of having exceptions.

What Is an Exception Chain?
An exception chain is a list of all the exceptions generated in response to a single root exception (say, a SQLException). As each exception is caught and converted to a higher-level exception for rethrowing, it's added to the chain. This provides a complete record of how an exception is handled (see Figure 1).

try {
stmt.executeUpdate(sql);
} catch (SQLException ex) {
throw new
EmployeeLookupException(
"Query failure",ex);
}

The Implementation
The exception chain is implemented as a linked list of exceptions in reverse order from last exception thrown to first. Each exception is a link in the chain. The first exception thrown that begins the chain can be of any type - there's no need for any special functionality - but all subsequent exceptions must have a way of referring to the previous exception so that the chain of exceptions can be maintained. In addition, there must be some means for accessing/examining the exception chain. I refer to exceptions that provide these things as being "chainable" - that is, an exception chain can be constructed using them.

For my purposes a "chainable" exception must do two things:

  1. Provide at least one constructor taking another (previous) exception as a parameter and storing it.
  2. Override each of the printStackTrace() methods to first print their own stack trace, then invoke the corresponding printStackTrace() method of the previous exception (given as a parameter in the constructor).
The first requirement enables the exception chain to be built. The second provides a simple means of displaying the results by invoking printStackTrace().

In practice, these simple rules allow chaining to be added to exception classes without forcing undue requirements on the users of those classes. A programmer doesn't need to know about exception chaining, even when using chainable exceptions. If chaining is used (by passing the previous exception to the new exception when converting), then the benefits are seen in the stack traces. If it's not used, there's no learning curve or overhead for the developer, and he or she is no worse off than if using nonchainable exceptions.

Any exception class can be written to meet the requirements described above, regardless of what its superclass is.

Let's examine a simple implementation of a chainable exception that extends Exception. The ChainedException (see Listing 1) can be used as a template when writing other chainable exceptions (e.g., copy the code overriding the printStackTrace() methods), or simply extended by those exceptions that would normally extend the Exception class.

Notice that the constructors take Throwables as parameters rather than Exceptions. This allows the "exception" chain to be made up of any classes that can be thrown in Java, including both compile time and runtime exceptions as well as Errors. The implementation of these constructors is straightforward; they save the reference to the given Throwable instance with the _previousThrowable member variable. This reference is used only by the printStackTrace() methods.

Also note that some constructors don't take any Exceptions or Throwables as a parameter. These constructors are used to create the root exception.

Server (and Non-GUI) Applications
Using exception chaining in server applications is simple. Build the chain as normal, and when logging exceptions be sure to use one of the printStackTrace() methods. There's no need to log each exception as they're caught. Only the last exception of the chain has to be logged, since it will display the message and call stack of each exception in the chain.

There's no harm if intermediate exceptions are logged individually, however; the worst that can happen is a slightly more cluttered log (see Figure 2). Server administrators are familiar with reading logs to determine errors, and are grateful for the extra information provided by using exception chaining.

The next section describes how a specialized dialog class can make exception chaining accessible in client programs.

Client Applications
One enormous benefit of the Java language is its resilience to errors. Java programs aren't generally "auto-terminated" as a result of an error; instead, the error is thrown (in the form of an exception) up the call stack to be handled. In a Java client application, if a runtime exception isn't handled, the main event dispatcher will print the exception's stack trace to standard out (or a Java console). This simple action is actually quite useful. While the user's button click won't appear to have done anything, at least a record of the error is available (if the Java console is visible and the user knows to look at it). Therefore, many programmers decide to handle all exceptions this way: log the exception and abort the action.

A better approach is to inform the user of any errors, usually via a dialog box. The best dialogs clearly indicate two things: what action failed, and why. I've implemented a dialog box (called ExceptionDialog) for use with exceptions that provide that information. It can be used equally with exception chains and single exceptions; it doesn't distinguish between the two.

To use the ExceptionDialog, a "try/catch" block is added to the individual GUI event handlers the programmer has registered. When an exception is caught by an event handler, an instance of ExceptionDialog is created (passing the exception as a parameter) and displayed. The title of the dialog (also passed in as a parameter to the constructor) indicates to the user what requested action has failed to occur because of the exception being thrown. The dialog message string is populated with the result of calling the exception's getLocalizedMessage() method, providing the second important piece of information - why that action couldn't be completed. Figure 3 shows an ExceptionDialog with details hidden.

try {
... event handler code ...
} catch (Exception ex) {
ExceptionDialog dlg =
new ExceptionDialog(
frame,ex,
"Look-up failed.");
dlg.show();
}

To examine the cause of the exception in more detail, the user clicks the "Show Details" button to expand the dialog. The expanded dialog (see Figure 4) displays the call stack of the exception and, if it's a chain of exceptions, the call stack of each exception in the chain. The information can be printed, or copied into an e-mail and sent to the user's help desk.

Listing 2 demonstrates exception chaining and use of the ExceptionDialog class in a GUI program. The BonusCalcException and EmployeeLookupException classes (not shown) both inherit from ChainedException.

The complete source code for all classes can be downloaded from www.JavaDevelopersJournal.com.

Where Have I Seen This Before?
The RemoteException in RMI and the ServletException from the Java Servlets API are both chainable classes. Sun refers to exceptions as being "nested" rather than "chained," but the intentions are the same.

Working on the Chain Gang
My own experience with exception chaining has shown it to be very valuable, and I tend to use it in most projects I'm involved with. However, I've found one common scenario that presents new hazards: distributed Java programs using RMI (remote method invocation).

The benefit of using RMI is that the distinction between local and remote objects is greatly reduced. It's not much more difficult to invoke a method on a remote object than a local object, except that the calling method must catch or throw RemoteException. Using exception chaining with exceptions that may be thrown during a remote method invocation offers the same benefits as with regular method invocations. It's easy to determine the root cause of errors even if they occurred in a remote object.

Unfortunately, while the sets of classes available to client and server applications overlap, they're not usually identical. Server programs have no need for GUI classes, and client programs have no need for database classes. The set of classes (or at least JAR files) available to the client is often intentionally stripped down to the minimum number required for its functionality to minimize its footprint. Therefore, if an exception chain containing a database-specific exception is thrown from the server to a remote client, it may not be possible to deal with it because the client application doesn't know what that database exception is. A ClassNotFoundException will be thrown when there's an attempt to unmarshal the unknown exception class.

Exception chaining can still be valuable in distributed applications. The easiest way to prevent the problem described above is for each application to be responsible for reporting its own exceptions. Methods that can be invoked remotely should log their internal exceptions and create a new exception for throwing remotely. The new exception should not chain the previous exception. This guarantees that no unknown exception types will be passed remotely by an exception chain.

Summary
Exception handling is often seen as a hindrance and treated as an afterthought. In fact, good exception-handling techniques can greatly simplify debugging. The exception-chaining technique is useful for both client and server components, making it easier to determine the root cause of exceptions without increasing the complexity of work required to handle them.

More Stories By Barry Mosher

Barry Mosher is a Java consultant in the San Francisco Bay Area. A Sun-certified Java programmer, Barry has more than seven years of programming experience, including three in Java.

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


@ThingsExpo Stories
The security devil is always in the details of the attack: the ones you've endured, the ones you prepare yourself to fend off, and the ones that, you fear, will catch you completely unaware and defenseless. The Internet of Things (IoT) is nothing if not an endless proliferation of details. It's the vision of a world in which continuous Internet connectivity and addressability is embedded into a growing range of human artifacts, into the natural world, and even into our smartphones, appliances, and physical persons. In the IoT vision, every new "thing" - sensor, actuator, data source, data con...
Technology is enabling a new approach to collecting and using data. This approach, commonly referred to as the "Internet of Things" (IoT), enables businesses to use real-time data from all sorts of things including machines, devices and sensors to make better decisions, improve customer service, and lower the risk in the creation of new revenue opportunities. In his General Session at Internet of @ThingsExpo, Dave Wagstaff, Vice President and Chief Architect at BSQUARE Corporation, discuss the real benefits to focus on, how to understand the requirements of a successful solution, the flow of ...
"BSQUARE is in the business of selling software solutions for smart connected devices. It's obvious that IoT has moved from being a technology to being a fundamental part of business, and in the last 18 months people have said let's figure out how to do it and let's put some focus on it, " explained Dave Wagstaff, VP & Chief Architect, at BSQUARE Corporation, in this SYS-CON.tv interview at @ThingsExpo, held Nov 4-6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
The major cloud platforms defy a simple, side-by-side analysis. Each of the major IaaS public-cloud platforms offers their own unique strengths and functionality. Options for on-site private cloud are diverse as well, and must be designed and deployed while taking existing legacy architecture and infrastructure into account. Then the reality is that most enterprises are embarking on a hybrid cloud strategy and programs. In this Power Panel at 15th Cloud Expo (http://www.CloudComputingExpo.com), moderated by Ashar Baig, Research Director, Cloud, at Gigaom Research, Nate Gordon, Director of T...

ARMONK, N.Y., Nov. 20, 2014 /PRNewswire/ --  IBM (NYSE: IBM) today announced that it is bringing a greater level of control, security and flexibility to cloud-based application development and delivery with a single-tenant version of Bluemix, IBM's platform-as-a-service. The new platform enables developers to build ap...

Focused on this fast-growing market’s needs, Vitesse Semiconductor Corporation (Nasdaq: VTSS), a leading provider of IC solutions to advance "Ethernet Everywhere" in Carrier, Enterprise and Internet of Things (IoT) networks, introduced its IStaX™ software (VSC6815SDK), a robust protocol stack to simplify deployment and management of Industrial-IoT network applications such as Industrial Ethernet switching, surveillance, video distribution, LCD signage, intelligent sensors, and metering equipment. Leveraging technologies proven in the Carrier and Enterprise markets, IStaX is designed to work ac...
"There is a natural synchronization between the business models, the IoT is there to support ,” explained Brendan O'Brien, Co-founder and Chief Architect of Aria Systems, in this SYS-CON.tv interview at the 15th International Cloud Expo®, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
C-Labs LLC, a leading provider of remote and mobile access for the Internet of Things (IoT), announced the appointment of John Traynor to the position of chief operating officer. Previously a strategic advisor to the firm, Mr. Traynor will now oversee sales, marketing, finance, and operations. Mr. Traynor is based out of the C-Labs office in Redmond, Washington. He reports to Chris Muench, Chief Executive Officer. Mr. Traynor brings valuable business leadership and technology industry expertise to C-Labs. With over 30 years' experience in the high-tech sector, John Traynor has held numerous...
Bit6 today issued a challenge to the technology community implementing Web Real Time Communication (WebRTC). To leap beyond WebRTC’s significant limitations and fully leverage its underlying value to accelerate innovation, application developers need to consider the entire communications ecosystem.
The 3rd International @ThingsExpo, co-located with the 16th International Cloud Expo - to be held June 9-11, 2015, at the Javits Center in New York City, NY - announces that it is now accepting Keynote Proposals. The Internet of Things (IoT) is the most profound change in personal and enterprise IT since the creation of the Worldwide Web more than 20 years ago. All major researchers estimate there will be tens of billions devices - computers, smartphones, tablets, and sensors - connected to the Internet by 2020. This number will continue to grow at a rapid pace for the next several decades.
The Internet of Things is not new. Historically, smart businesses have used its basic concept of leveraging data to drive better decision making and have capitalized on those insights to realize additional revenue opportunities. So, what has changed to make the Internet of Things one of the hottest topics in tech? In his session at @ThingsExpo, Chris Gray, Director, Embedded and Internet of Things, discussed the underlying factors that are driving the economics of intelligent systems. Discover how hardware commoditization, the ubiquitous nature of connectivity, and the emergence of Big Data a...
Almost everyone sees the potential of Internet of Things but how can businesses truly unlock that potential. The key will be in the ability to discover business insight in the midst of an ocean of Big Data generated from billions of embedded devices via Systems of Discover. Businesses will also need to ensure that they can sustain that insight by leveraging the cloud for global reach, scale and elasticity.
SYS-CON Events announced today that Windstream, a leading provider of advanced network and cloud communications, has been named “Silver Sponsor” of SYS-CON's 16th International Cloud Expo®, which will take place on June 9–11, 2015, at the Javits Center in New York, NY. Windstream (Nasdaq: WIN), a FORTUNE 500 and S&P 500 company, is a leading provider of advanced network communications, including cloud computing and managed services, to businesses nationwide. The company also offers broadband, phone and digital TV services to consumers primarily in rural areas.
SYS-CON Events announced today that IDenticard will exhibit at SYS-CON's 16th International Cloud Expo®, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. IDenticard™ is the security division of Brady Corp (NYSE: BRC), a $1.5 billion manufacturer of identification products. We have small-company values with the strength and stability of a major corporation. IDenticard offers local sales, support and service to our customers across the United States and Canada. Our partner network encompasses some 300 of the world's leading systems integrators and security s...
IoT is still a vague buzzword for many people. In his session at @ThingsExpo, Mike Kavis, Vice President & Principal Cloud Architect at Cloud Technology Partners, discussed the business value of IoT that goes far beyond the general public's perception that IoT is all about wearables and home consumer services. He also discussed how IoT is perceived by investors and how venture capitalist access this space. Other topics discussed were barriers to success, what is new, what is old, and what the future may hold. Mike Kavis is Vice President & Principal Cloud Architect at Cloud Technology Pa...
Cloud Expo 2014 TV commercials will feature @ThingsExpo, which was launched in June, 2014 at New York City's Javits Center as the largest 'Internet of Things' event in the world. The next @ThingsExpo will take place November 4-6, 2014, at the Santa Clara Convention Center, in Santa Clara, California. Since its launch in 2008, Cloud Expo TV commercials have been aired and CNBC, Fox News Network, and Bloomberg TV. Please enjoy our 2014 commercial.
From a software development perspective IoT is about programming "things," about connecting them with each other or integrating them with existing applications. In his session at @ThingsExpo, Yakov Fain, co-founder of Farata Systems and SuranceBay, will show you how small IoT-enabled devices from multiple manufacturers can be integrated into the workflow of an enterprise application. This is a practical demo of building a framework and components in HTML/Java/Mobile technologies to serve as a platform that can integrate new devices as they become available on the market.
The 3rd International Internet of @ThingsExpo, co-located with the 16th International Cloud Expo - to be held June 9-11, 2015, at the Javits Center in New York City, NY - announces that its Call for Papers is now open. The Internet of Things (IoT) is the biggest idea since the creation of the Worldwide Web more than 20 years ago.
Located in booth #314, the Bsquare team will present DataV demos and discuss how DataV will help customers put their data to work to improve business outcomes. DataV is unlocking new initiatives across a wide landscape of customers in industries such as industrial manufacturing, transportation, retail and mobile. The solution is designed to complement a new project start or help to enrich an existing machine investment.
The Physical Web incorporates beacons that can be put in any small retail store, for example, so that every store now has "an app" for its customers. In this Birds-of-a-Feather session at Internet of @ThingsExpo, Scott Jenson, Product Designer at Google, will discuss the Physical Web and how it is an open standard so any device can broadcast a URL wirelessly, so any phone/tablet/watch nearby can see, and rank those devices. When the user taps on one, they just go to that web page. It's really that simple. It's about thinking small, enabling micro-information (what is in my prescription bottle...