Retrowing Exceptions
Javelin-Throwing.gif

How to rethrow an exception without wrapping it.

Occasionally you need to intercept all exceptions, do something with them, and allow them to propagate. One way is to catch Throwable. But how do you rethrow it, without declaring Throwable in the current method and everything above it on the call stack ? A better way is to implement this code below and call rethrowException(t);

// required to avoid startup issues with the security manager.
    static class UnsafeHolder {
        static final sun.misc.Unsafe unsafe;
 
        static {
            try {
                Field field = sun.misc.Unsafe.class.getDeclaredField("theUnsafe");
                field.setAccessible(true);
                unsafe = (sun.misc.Unsafe) field.get(null);
            } catch (Exception e) {
                throw new AssertionError(e);
            }
        }
 
        private UnsafeHolder() {
        }
    }
 
    /**
     * Rethrow any throwable, even checked exceptions blindly.
     *
     * @param t
     * @return
     */
    public static InternalError rethrowException(Throwable t) {
        UnsafeHolder.unsafe.throwException(t);
        // should never get there.
        throw new InternalError();
    }

Some Do's and Don't's with Exceptions

1. Unless you have a very good reason to catch an exception, DON'T.
2. If you can correct the problem implied by the exception. eat the exception, because you fixed it.
3. If you can provide additional information about the exception. catch the exception, and re-throw it as an inner exception with more information. This is a very good reason to catch an exception, but note that we are still re-throwing it!
4.Always try to catch specific exceptions. Avoid catching System.Exception whenever possible.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License