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
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);
        }

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.

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