Welcome!

Java Authors: Lori MacVittie, Roger Strukhoff, Esmeralda Swartz, Trevor Parsons, Sandi Mappic

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 will greatly expand the opportunities for data collection and new business models driven off of that data. In her session at Internet of @ThingsExpo, Esmeralda Swartz, CMO of MetraTech, will discuss 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! Speaker Bio: Esmeralda Swartz, CMO of MetraTech, has spent 16 years as a marketing, product management, and busin...
Samsung VP Jacopo Lenzi, who headed the company's recent SmartThings acquisition under the auspices of Samsung's Open Innovaction Center (OIC), answered a few questions we had about the deal. This interview was in conjunction with our interview with SmartThings CEO Alex Hawkinson. IoT Journal: SmartThings was developed in an open, standards-agnostic platform, and will now be part of Samsung's Open Innovation Center. Can you elaborate on your commitment to keep the platform open? Jacopo Lenzi: Samsung recognizes that true, accelerated innovation cannot be driven from one source, but requires a...
SYS-CON Events announced today that Red Hat, the world's leading provider of open source solutions, will exhibit at Internet of @ThingsExpo, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Red Hat is the world's leading provider of open source software solutions, using a community-powered approach to reliable and high-performing cloud, Linux, middleware, storage and virtualization technologies. Red Hat also offers award-winning support, training, and consulting services. As the connective hub in a global network of enterprises, partners, a...
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 Internet of @ThingsExpo, Robin Raymond, Chief Architect at Hookflash Inc., will walk through the shifting landscape of traditional telephone a...
SYS-CON Events announced today that Matrix.org has been named “Silver Sponsor” of Internet of @ThingsExpo, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Matrix is an ambitious new open standard for open, distributed, real-time communication over IP. It defines a new approach for interoperable Instant Messaging and VoIP based on pragmatic HTTP APIs and WebRTC, and provides open source reference implementations to showcase and bootstrap the new standard. Our focus is on simplicity, security, and supporting the fullest feature set.
BSQUARE is a global leader of embedded software solutions. We enable smart connected systems at the device level and beyond that millions use every day and provide actionable data solutions for the growing Internet of Things (IoT) market. We empower our world-class customers with our products, services and solutions to achieve innovation and success. For more information, visit www.bsquare.com.
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 style...
SYS-CON Events announced today that SOA Software, an API management leader, will exhibit at SYS-CON's 15th International Cloud Expo®, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. SOA Software is a leading provider of API Management and SOA Governance products that equip business to deliver APIs and SOA together to drive their company to meet its business strategy quickly and effectively. SOA Software’s technology helps businesses to accelerate their digital channels with APIs, drive partner adoption, monetize their assets, and achieve a...
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.
SYS-CON Events announced today that Utimaco will exhibit at SYS-CON's 15th International Cloud Expo®, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Utimaco is a leading manufacturer of hardware based security solutions that provide the root of trust to keep cryptographic keys safe, secure critical digital infrastructures and protect high value data assets. Only Utimaco delivers a general-purpose hardware security module (HSM) as a customizable platform to easily integrate into existing software solutions, embed business logic and build s...
Connected devices are changing the way we go about our everyday life, from wearables to driverless cars, to smart grids and entire industries revolutionizing business opportunities through smart objects, capable of two-way communication. But what happens when objects are given an IP-address, and we rely on that connection, sometimes with our lives? How do we secure those vast data infrastructures and safe-keep the privacy of sensitive information? This session will outline how each and every connected device can uphold a core root of trust via a unique cryptographic signature – a “bir...
Internet of @ThingsExpo Silicon Valley announced on Thursday its first 12 all-star speakers and sessions for its upcoming event, which will take place November 4-6, 2014, at the Santa Clara Convention Center in California. @ThingsExpo, the first and largest IoT event in the world, debuted at the Javits Center in New York City in June 10-12, 2014 with over 6,000 delegates attending the conference. Among the first 12 announced world class speakers, IBM will present two highly popular IoT sessions, which will take place November 4-6, 2014 at the Santa Clara Convention Center in Santa Clara, Calif...
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.
WebRTC defines no default signaling protocol, causing fragmentation between WebRTC silos. SIP and XMPP provide possibilities, but come with considerable complexity and are not designed for use in a web environment. In his session at Internet of @ThingsExpo, Matthew Hodgson, technical co-founder of the Matrix.org, will discuss how Matrix is a new non-profit Open Source Project that defines both a new HTTP-based standard for VoIP & IM signaling and provides reference implementations.

SUNNYVALE, Calif., Oct. 20, 2014 /PRNewswire/ -- Spansion Inc. (NYSE: CODE), a global leader in embedded systems, today added 96 new products to the Spansion® FM4 Family of flexible microcontrollers (MCUs). Based on the ARM® Cortex®-M4F core, the new MCUs boast a 200 MHz operating frequency and support a diverse set of on-chip peripherals for enhanced human machine interfaces (HMIs) and machine-to-machine (M2M) communications. The rich set of periphera...

SYS-CON Events announced today that Aria Systems, the recurring revenue expert, has been named "Bronze Sponsor" of SYS-CON's 15th International Cloud Expo®, which will take place on November 4-6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Aria Systems helps leading businesses connect their customers with the products and services they love. Industry leaders like Pitney Bowes, Experian, AAA NCNU, VMware, HootSuite and many others choose Aria to power their recurring revenue business and deliver exceptional experiences to their customers.
The Internet of Things (IoT) is going to require a new way of thinking and of developing software for speed, security and innovation. This requires IT leaders to balance business as usual while anticipating for the next market and technology trends. Cloud provides the right IT asset portfolio to help today’s IT leaders manage the old and prepare for the new. Today the cloud conversation is evolving from private and public to hybrid. This session will provide use cases and insights to reinforce the value of the network in helping organizations to maximize their company’s cloud experience.
The Internet of Things (IoT) is making everything it touches smarter – smart devices, smart cars and smart cities. And lucky us, we’re just beginning to reap the benefits as we work toward a networked society. However, this technology-driven innovation is impacting more than just individuals. The IoT has an environmental impact as well, which brings us to the theme of this month’s #IoTuesday Twitter chat. The ability to remove inefficiencies through connected objects is driving change throughout every sector, including waste management. BigBelly Solar, located just outside of Boston, is trans...
SYS-CON Events announced today that Matrix.org has been named “Silver Sponsor” of Internet of @ThingsExpo, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Matrix is an ambitious new open standard for open, distributed, real-time communication over IP. It defines a new approach for interoperable Instant Messaging and VoIP based on pragmatic HTTP APIs and WebRTC, and provides open source reference implementations to showcase and bootstrap the new standard. Our focus is on simplicity, security, and supporting the fullest feature set.
Predicted by Gartner to add $1.9 trillion to the global economy by 2020, the Internet of Everything (IoE) is based on the idea that devices, systems and services will connect in simple, transparent ways, enabling seamless interactions among devices across brands and sectors. As this vision unfolds, it is clear that no single company can accomplish the level of interoperability required to support the horizontal aspects of the IoE. The AllSeen Alliance, announced in December 2013, was formed with the goal to advance IoE adoption and innovation in the connected home, healthcare, education, aut...