harmony-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Jesse Wilson <jessewil...@google.com>
Subject SneakyThrow!
Date Fri, 13 Nov 2009 20:24:06 GMT
Harmony team,

In the process of fixing a bug, I just checked in
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
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()) {

            Throwable thrown = null;
            try {
            } catch (Throwable e) {
                thrown = e;
            buf = null;

            try {
            } 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) {

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!


PS - SneakyThrow is based on puzzler #43 in the fine Java Puzzlers book.

  • Unnamed multipart/alternative (inline, None, 0 bytes)
View raw message