On 13/Nov/2009 20:24, Jesse Wilson wrote: > Harmony team, > > In the process of fixing a bug, I just checked in > SneakyThrow<http://svn.apache.org/viewvc/harmony/enhanced/classlib/trunk/modules/luni/src/main/java/org/apache/harmony/luni/util/SneakyThrow.java?revision=835972&view=markup>. > This is a weird API that probably won't see much use. But it > *is*interesting and something you might want to take a look at. With > regular > code, coping with exceptions correctly is pain. Consider the full body of > BufferedWriter.close(), in particular the last 10 lines. > > public void close() throws IOException { > synchronized (lock) { > if (isClosed()) { > return; > } > > Throwable thrown = null; > try { > flushInternal(); > } catch (Throwable e) { > thrown = e; > } > buf = null; > > try { > out.close(); > } catch (Throwable e) { > if (thrown == null) { > thrown = e; > } > } > out = null; > > if (thrown != null) { > if (thrown instanceof IOException) { > throw (IOException) thrown; > } else if (thrown instanceof RuntimeException) { > throw (RuntimeException) thrown; > } else if (thrown instanceof Error) { > throw (Error) thrown; > } else { > throw new AssertionError(); > } > } > } > } > > This new API shortens that last section dramatically: > > if (thrown != null) { > SneakyThrow.sneakyThrow(thrown); > }
The difference I see, by just staring at the code and without running it, is that if the 'thrown' Throwable that was caught earlier is not one of the tested types (IOException | RuntimeException | Error) then the original code throws an AssertionError, whereas sneaky will re-throw the raised type. Not sure why the original has AssertionError... > This comes up more often in library code, where it's necessary to cleanly > close resources without losing exceptions. SneakyThrow increases the chances > that we'll do the right thing when it comes to exception handling. Please > don't use it, unless you really, really need to! > > Cheers, > Jesse > > PS - SneakyThrow is based on puzzler #43 in the fine Java Puzzlers book. Aww, I thought you'd at least have posted an affiliate link too?! <g> Regards, Tim