
package uk.co.wingpath.util;

/**
* This class implements {@link java.lang.Thread.UncaughtExceptionHandler}
* by printing a stack trace and then calling {@link System#exit System.exit}.
*/
public class UncaughtExceptionHandler
    implements Thread.UncaughtExceptionHandler
{
    private Reporter reporter;

    /**
    * Constructs an {@code UncaughtExceptionHandler} using the specified
    * reporter.
    * <p>An uncaught exception is reported using the
    * {@link Reporter#fatal(Throwable,String,Object...) Reporter.fatal} method.
    * <p>After reporting the exception, {@link System#exit} is called.
    * <p>Do not use this handler as the default exception handler (i.e. do
    * not pass it to {@link Thread#setDefaultUncaughtExceptionHandler}), as it
    * would then be used for shutdown-hook threads, and if you call
    * {@code System.exit} from a shutdown hook the whole shutdown freezes
    * (needing a SIGKILL to end the process).
    * @param reporter where to report exceptions.
    */
    public UncaughtExceptionHandler (Reporter reporter)
    {
        if (reporter == null)
            throw new NullPointerException ("reporter must not be null");
        this.reporter = reporter;
    }

    public void uncaughtException (Thread t, Throwable e)
    {
        reporter.fatal (e, "Uncaught exception in thread '%s'", t.getName ());
        System.exit (1);
    }
}

