There are two solutions I've seen to this problem. The first being what I consider the "standard java" way. You completely ignore any exception encountered when closing a resource in the finally block, and let the original exception pass through. Although incorrect in a few use cases, this behavior is reasonable for a lot of other use cases.
The other mechanism is to store all exceptions that happen using some form of wrapper class: interface Function<U,T> { public U call(T arg); } interface Result<T> { public boolean isSuccess(); public T getValue(); public List<Exception> getExceptions(); public <U> Result<U> map(Function<U,T> function); } The idea here is you code in such a way the exceptions are aggregated as they occur and you deal with them when finished processing data. You do this using continuation style (This is more common in a language supporting code blocks/closures) e.g. Result<MyObject> result = someApiCall(); result = result.map(new Function<SomeOtherType, MyObject>() { public SomeOtherType call(MyObject arg) { //Do stuff with the result. This won't actually be called if there was a previous error. } }); if(!result.isSuccess()) { figureOutWhatToDo(result.getExceptions()); } else { return result.getValue(); } On Tue, Jun 2, 2009 at 8:01 PM, Tim <javaposse.t...@spamgourmet.com> wrote: > > In Joshua Bloch's Automatic Resource Management proposal > (http://docs.google.com/Doc?id=ddv8ts74_3fs7483dp) for project Coin he > wrote: > > Even the "correct" idioms for manual resource management are > deficient: > if an exception is thrown in the try block, and another when > closing the > resource in the finally block, the second exception supplants the > first, making it difficult to determine the real cause of the > trouble. > In other words, by responsibly closing your resource even during > some > catastrophic event, you can actually erase all record of the > event, > resulting in many wasted hours of debugging. While it is possible > to > write code to suppress the second exception in favor of the first, > virtually no one does, as it is just too verbose. This is not a > theoretical problem; it has greatly complicated the debugging of > large > systems. > > I just encountered this problem: Some code threw an exception creating > a zip. > The ZipOutputStream was closed in a finally block and the real > exception > was replaced by one complaining that there were no entries in the zip. > > Does anyone do the "right" thing? What are the best idioms or helper > methods/classes to do this? > > > > --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "The Java Posse" group. To post to this group, send email to javaposse@googlegroups.com To unsubscribe from this group, send email to javaposse+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/javaposse?hl=en -~----------~----~----~----~------~----~------~--~---