获取线程运行时异常

x33g5p2x  于2022-03-29 转载在 其他  
字(1.8k)|赞(0)|评价(0)|浏览(233)

一 运行时异常 API

// 为某个特定线程指定 UncaughtExceptionHandler
public void setUncaughtExceptionHandler(UncaughtExceptionHandler eh)
// 设置全局UncaughtExceptionHandler
public static void setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler eh)
// 获取特定线程的 UncaughtExceptionHandler
public UncaughtExceptionHandler getUncaughtExceptionHandler()
// 获取全局的 UncaughtExceptionHandler
public static UncaughtExceptionHandler getDefaultUncaughtExceptionHandler()

二 点睛

线程在执行单元中不允许抛出 checked 异常,线程运行在自己的上下文中,派生它的线程将无法直接获得它允许中出现的异常信息。Java 为我们提供了 UncaughtExceptionHandler 接口,从而得知是哪个线程在运行时出错,以及出现了什么样的错误。

@FunctionalInterface
public interface UncaughtExceptionHandler {
    /**
     * Method invoked when the given thread terminates due to the
     * given uncaught exception.
     * <p>Any exception thrown by this method will be ignored by the
     * Java Virtual Machine.
     * @param t the thread
     * @param e the exception
     */
    void uncaughtException(Thread t, Throwable e);
}

上述代码中,UncaughtExceptionHandler 是一个 FunctionalInterface,只有一个抽象方法,该回调接口被  Thread 中的 dispatchUncaughtException 方法调用。

/**
* Dispatch an uncaught exception to the handler. This method is
* intended to be called only by the JVM.
*/
private void dispatchUncaughtException(Throwable e) {
    getUncaughtExceptionHandler().uncaughtException(this, e);
}

当线程在运行过程中出现异常时,JVM 会调用 dispatchUncaughtException 方法,该方法会将对应的线程实例以及异常信息传递给接口。

三 实战

1 代码

package concurrent;

import java.util.concurrent.TimeUnit;

public class UncatchExceptionHandlerDemo {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(1 / 0);
        });

        thread.setUncaughtExceptionHandler((t, e) -> {
            System.out.println(t.getName() + " occur exception");
            e.printStackTrace();
        });

        thread.start();
    }
}

2 测试

Thread-0 occur exception
java.lang.ArithmeticException: / by zero
    at concurrent.UncatchExceptionHandlerDemo.lambda$main$0(UncatchExceptionHandlerDemo.java:14)
    at java.lang.Thread.run(Thread.java:748)

相关文章

微信公众号

最新文章

更多