Path: csiph.com!x330-a1.tempe.blueboxinc.net!usenet.pasdenom.info!weretis.net!feeder4.news.weretis.net!eternal-september.org!feeder.eternal-september.org!.POSTED!not-for-mail From: Daniele Futtorovic Newsgroups: comp.lang.java.programmer Subject: Re: Thumbs up for suppressable exceptions in JDK 1.7 Date: Thu, 29 Sep 2011 18:05:09 +0200 Organization: A noiseless patient Spider Lines: 57 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit Injection-Date: Thu, 29 Sep 2011 16:06:39 +0000 (UTC) Injection-Info: mx04.eternal-september.org; posting-host="AUyBsac4Bvz0HEr1sKU8og"; logging-data="15295"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1/Ag2zXjml63EnhDSDbS9sp" User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.2.23) Gecko/20110920 Thunderbird/3.1.15 In-Reply-To: Cancel-Lock: sha1:fhs1Pz/N1r5CzNY/Vdb7Ves83Sg= Xref: x330-a1.tempe.blueboxinc.net comp.lang.java.programmer:8398 On 27/09/2011 21:43, Tom Anderson allegedly wrote: > On Tue, 27 Sep 2011, Roedy Green wrote: > >> On Tue, 27 Sep 2011 09:31:03 +0200, Jan Burse >> wrote, quoted or indirectly quoted someone who said : >> >>> Was just playing around with suppressable exceptions in JDK 1.7. This >>> looks like a great improvement for bug hunting! >>> ... 5 more >> >> I think you need some exposition on why this is a good thing. > > It avoids this common mistake: > > try { > doSomethingWhichMightThrowAnException(); > } > finally { > doSomeCleanupWhichMightThrowAnException(); > } > > In that code, if both methods throw an exception, you will only see the > second. The first exception - the one which actually caused the problem > - will be lost. It's as if the VM has a very short attention span, and > can only focus on whatever exception was most recently thrown. > > In Java 7, you can put the cleanup into the close() method of an > (Auto)Closeable, and use the try-with-resources form: > > class Thing implements AutoCloseable { > public void close() throws AnException { > doSomeCleanupWhichMightThrowAnException(); > } > } > > try (Thing t = new Thing()) { > doSomethingWhichMightThrowAnException(); > } > > There, the compiler will arrange things so that if close() does throw an > exception, it will be 'suppressed', and tagged on to the exception > coming from doSomethingWhichMightThrowAnException() as a suppressed > exception. > > tom > Indeed, but even more generally, we can from now on register "suppressed" exceptions ourselves, as Jan's code and the JSE7 Javadoc for java.lang.Throwable show. Great Thing IMHO. Closes a hole that's been lurking there for a very long time. Thanks Jan for bringing this to my attention. -- DF. Determinism trumps correctness.