This is a concept I like very much. We did it years ago in PowerBuilder, and they didn't even have Exceptions! The idea is important with layered systems with long call chains. Say a very low level exception happens way down the call chain. The next method up the chain catches it and throws another exception that explains the problem at a higher level. Then the next method up does the same. For example: lowest: Cannot connect to database middle: Cannot retrieve user information highest: Cannot log in to system At the end of this chain, the user sees a message that means something to them. But it might be interesting to the techies to know why. So when each method throws its higher level exception ,it can chain in the one it caught. Then some piece of code can call getCause to get the next level down, and getCause on that to get the next, and so on. We have implemented error messages that show the last message "Cannot log into system" and have a button to display the whole chain. If a user gets on the phone with tech support, we can ask them to hit the button and read the entire chain. In one Java implementation (long before 1.4) we kept a list of stack traces converted to text instead of a chain of Exceptions, because Exceptions didn't serialize well to go across distributed systems like EJB. Sorry, longish answer. Did that makes sense?
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
In Java, Chaining occurs when you catch one Exception and throw a new Exception from the catch.
Before jdk 1.4, you had to make the new exception capable of nesting the original exception and set it in before you threw it or all data from the original Exception is lost. (And any clear indication of what happened) In addition, everyone doing this had to write specific code to: 1) Hold the original Exception 2) Set and Get the original Exception 3) either override getMessage and printStackTrace() or do a dance when the exception was printed to print the stackTrace of the Original Exception and the seconadray exception. Well, in JDK 1.4, Throwable now has a nested Exception, the getMessage and printStackTrace automatically walk through the nested exceptions and you get all exceptions that occur. The only thing you need to do is to add two more constructors to your Exception
So, the above code becomes:
Now when you finally print the stackTrace on the thrown UserLoginException, you get the trace from the SQLException as well.