Returns wrapped runnable that ensures that if an exception occurs during the execution, the specified exception handler is invoked. - Java java.lang

Java examples for java.lang:Exception

Description

Returns wrapped runnable that ensures that if an exception occurs during the execution, the specified exception handler is invoked.

Demo Code

/*//  w ww.  j a va  2  s . c  o m
 * Written by Dawid Kurzyniec and released to the public domain, as explained
 * at http://creativecommons.org/licenses/publicdomain
 */

public class Main{
    /**
     * Returns wrapped runnable that ensures that if an exception occurs
     * during the execution, the specified exception handler is invoked.
     * @param runnable runnable for which exceptions are to be intercepted
     * @param handler the exception handler to call when exception occurs
     *        during execution of the given runnable
     * @return wrapped runnable
     */
    public static Runnable assignExceptionHandler(final Runnable runnable,
            final UncaughtExceptionHandler handler) {
        if (runnable == null || handler == null) {
            throw new NullPointerException();
        }
        return new Runnable() {
            public void run() {
                try {
                    runnable.run();
                } catch (Throwable error) {
                    try {
                        handler.uncaughtException(Thread.currentThread(),
                                error);
                    } catch (Throwable ignore) {
                    }
                }
            }
        };
    }
}

Related Tutorials