Welcome!

Java Authors: Pat Romanski, Victoria Livschitz, Carmen Gonzalez, Elizabeth White, Liz McMillan

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 Internet of Things is tied together with a thin strand that is known as time. Coincidentally, at the core of nearly all data analytics is a timestamp. When working with time series data there are a few core principles that everyone should consider, especially across datasets where time is the common boundary. In his session at Internet of @ThingsExpo, Jim Scott, Director of Enterprise Strategy & Architecture at MapR Technologies, discussed single-value, geo-spatial, and log time series data. By focusing on enterprise applications and the data center, he will use OpenTSDB as an example t...
How do APIs and IoT relate? The answer is not as simple as merely adding an API on top of a dumb device, but rather about understanding the architectural patterns for implementing an IoT fabric. There are typically two or three trends: Exposing the device to a management framework Exposing that management framework to a business centric logic Exposing that business layer and data to end users. This last trend is the IoT stack, which involves a new shift in the separation of what stuff happens, where data lives and where the interface lies. For instance, it's a mix of architectural styles ...
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.
An entirely new security model is needed for the Internet of Things, or is it? Can we save some old and tested controls for this new and different environment? In his session at @ThingsExpo, New York's at the Javits Center, Davi Ottenheimer, EMC Senior Director of Trust, reviewed hands-on lessons with IoT devices and reveal a new risk balance you might not expect. Davi Ottenheimer, EMC Senior Director of Trust, has more than nineteen years' experience managing global security operations and assessments, including a decade of leading incident response and digital forensics. He is co-author of t...
The Internet of Things will greatly expand the opportunities for data collection and new business models driven off of that data. In her session at @ThingsExpo, Esmeralda Swartz, CMO of MetraTech, discussed how for this to be effective you not only need to have infrastructure and operational models capable of utilizing this new phenomenon, but increasingly service providers will need to convince a skeptical public to participate. Get ready to show them the money!
The Internet of Things will put IT to its ultimate test by creating infinite new opportunities to digitize products and services, generate and analyze new data to improve customer satisfaction, and discover new ways to gain a competitive advantage across nearly every industry. In order to help corporate business units to capitalize on the rapidly evolving IoT opportunities, IT must stand up to a new set of challenges. In his session at @ThingsExpo, Jeff Kaplan, Managing Director of THINKstrategies, will examine why IT must finally fulfill its role in support of its SBUs or face a new round of...
One of the biggest challenges when developing connected devices is identifying user value and delivering it through successful user experiences. In his session at Internet of @ThingsExpo, Mike Kuniavsky, Principal Scientist, Innovation Services at PARC, described an IoT-specific approach to user experience design that combines approaches from interaction design, industrial design and service design to create experiences that go beyond simple connected gadgets to create lasting, multi-device experiences grounded in people's real needs and desires.
Enthusiasm for the Internet of Things has reached an all-time high. In 2013 alone, venture capitalists spent more than $1 billion dollars investing in the IoT space. With "smart" appliances and devices, IoT covers wearable smart devices, cloud services to hardware companies. Nest, a Google company, detects temperatures inside homes and automatically adjusts it by tracking its user's habit. These technologies are quickly developing and with it come challenges such as bridging infrastructure gaps, abiding by privacy concerns and making the concept a reality. These challenges can't be addressed w...
The Domain Name Service (DNS) is one of the most important components in networking infrastructure, enabling users and services to access applications by translating URLs (names) into IP addresses (numbers). Because every icon and URL and all embedded content on a website requires a DNS lookup loading complex sites necessitates hundreds of DNS queries. In addition, as more internet-enabled ‘Things' get connected, people will rely on DNS to name and find their fridges, toasters and toilets. According to a recent IDG Research Services Survey this rate of traffic will only grow. What's driving t...
Connected devices and the Internet of Things are getting significant momentum in 2014. In his session at Internet of @ThingsExpo, Jim Hunter, Chief Scientist & Technology Evangelist at Greenwave Systems, examined three key elements that together will drive mass adoption of the IoT before the end of 2015. The first element is the recent advent of robust open source protocols (like AllJoyn and WebRTC) that facilitate M2M communication. The second is broad availability of flexible, cost-effective storage designed to handle the massive surge in back-end data in a world where timely analytics is e...
Scott Jenson leads a project called The Physical Web within the Chrome team at Google. Project members are working to take the scalability and openness of the web and use it to talk to the exponentially exploding range of smart devices. Nearly every company today working on the IoT comes up with the same basic solution: use my server and you'll be fine. But if we really believe there will be trillions of these devices, that just can't scale. We need a system that is open a scalable and by using the URL as a basic building block, we open this up and get the same resilience that the web enjoys.
We are reaching the end of the beginning with WebRTC, and real systems using this technology have begun to appear. One challenge that faces every WebRTC deployment (in some form or another) is identity management. For example, if you have an existing service – possibly built on a variety of different PaaS/SaaS offerings – and you want to add real-time communications you are faced with a challenge relating to user management, authentication, authorization, and validation. Service providers will want to use their existing identities, but these will have credentials already that are (hopefully) i...
"Matrix is an ambitious open standard and implementation that's set up to break down the fragmentation problems that exist in IP messaging and VoIP communication," explained John Woolf, Technical Evangelist at Matrix, in this SYS-CON.tv interview at @ThingsExpo, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
Cultural, regulatory, environmental, political and economic (CREPE) conditions over the past decade are creating cross-industry solution spaces that require processes and technologies from both the Internet of Things (IoT), and Data Management and Analytics (DMA). These solution spaces are evolving into Sensor Analytics Ecosystems (SAE) that represent significant new opportunities for organizations of all types. Public Utilities throughout the world, providing electricity, natural gas and water, are pursuing SmartGrid initiatives that represent one of the more mature examples of SAE. We have s...
P2P RTC will impact the landscape of communications, shifting from traditional telephony style communications models to OTT (Over-The-Top) cloud assisted & PaaS (Platform as a Service) communication services. The P2P shift will impact many areas of our lives, from mobile communication, human interactive web services, RTC and telephony infrastructure, user federation, security and privacy implications, business costs, and scalability. In his session at @ThingsExpo, Robin Raymond, Chief Architect at Hookflash, will walk through the shifting landscape of traditional telephone and voice services ...
Explosive growth in connected devices. Enormous amounts of data for collection and analysis. Critical use of data for split-second decision making and actionable information. All three are factors in making the Internet of Things a reality. Yet, any one factor would have an IT organization pondering its infrastructure strategy. How should your organization enhance its IT framework to enable an Internet of Things implementation? In his session at Internet of @ThingsExpo, James Kirkland, Chief Architect for the Internet of Things and Intelligent Systems at Red Hat, described how to revolutioniz...
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 definition of IoT is not new, in fact it’s been around for over a decade. What has changed is the public's awareness that the technology we use on a daily basis has caught up on the vision of an always on, always connected world. If you look into the details of what comprises the IoT, you’ll see that it includes everything from cloud computing, Big Data analytics, “Things,” Web communication, applications, network, storage, etc. It is essentially including everything connected online from hardware to software, or as we like to say, it’s an Internet of many different things. The difference ...
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.
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.