javaexceptionddlutilsnested-exceptions

Nested Exception vs modern (Java SE 7) exceptions


Question

What are the advantages and disadvantages of exceptions with context vs nested exceptions?

Why I care

As a developer who doesn't have a background in or know the background of Java, I have stumbled upon a possible opportunity to update an open source project's exception handling, but I wish to ensure that the change I would make is beneficial.

The project in question is ddlutils. It currently uses org.apache.commons.lang.exception which states:

"Provides JDK 1.4 style Nested Exception functionality for those on prior Java versions."

The current version of Commons Lang (3.1 at time of writing) uses org.apache.commons.lang3.exception which states:

"Contains the concept of an exception with context i.e. such an exception will contain a map with keys and values. This provides an easy way to pass valuable state information at exception time in useful form to a calling process."


Solution

  • Discussing this you should be aware JDK1.4 as released about 10 years ago. It invented exception chaining wich simply means you have a contructor that takes a cause exception. And then a nice compound stack trace for all that stuff is printed. Before JDK1.4 many such implementations had existed in the JDK and those have been unifued to a single consistent solution. Now what commons lang did was to provide some simlar base classes to get this idea to older JDKs. However since the many things happened:

    So simply no one is interessted in 'prior JDK 1.4' versions any more.

    Now on the other hand this exception with context thing has nothing to do with any JDK version. It's again base classes for exceptions, but it has a Map in which to put things. Normally this is implemented by special exception types having additional fields. This is type safe, nice and clean. Having a map on every exception, means never knowing what will be in this map. I can't think of any benefit this provides. So, if you do not have a really great plan to use it, I wouldn't recommend it.