你知道如何使用UncaughtExceptionHandler嗎?那就趕快來看看

下面,我們將給出一個例項,來演示如何使用UncaughtExceptionHandler。

package com。wangwenjun。concurrent。chapter07;

import java。util。concurrent。TimeUnit;

public class CaptureThreadException

{

public static void main(String[]args)

{

//①設定回撥介面

Thread。setDefaultUncaughtExceptionHandler((t,e)->)

{

System。out。println(t。getName()+“occur excepti)

e。printStackTrace();

});

final Thread thread=new Thread(()->)

{

try

{

TimeUnit。SECONDS。sleep(2);

}catch(InterruptedException e)

{

}

//②這裡會出現unchecked異常

//here will throw unchecked exception。

System。out。println(1/0);

},”Test-Thread“);

thread。start();

}

}

你知道如何使用UncaughtExceptionHandler嗎?那就趕快來看看

執行上面的程式,執行緒Test-Thread在執行兩秒之後會丟擲一個unchecked異常,我們設定的回撥介面將獲得該異常資訊,程式的執行結果如下:

Test-Thread occur exception

java。lang。ArithmeticException:/by zero

at com。wangwenjun。concurrent。chapter06。CaptureThreadExce

(CaptureThreadException。java:26)

at com。wangwenjun。concurrent。chapter06。CaptureThreadExce

531885035。run(Unknown Source)

at java。lang。Thread。run(Thread。java:745)

在平時的工作中,這種設計方式是比較常見的,尤其是那種非同步執行方法,比如Google的guava toolkit就提供了EventBus。

你知道如何使用UncaughtExceptionHandler嗎?那就趕快來看看

在EventBus中事件源和實踐的subscriber兩者藉助於EventBus實現了完全的解耦合,但是在subscriber執行任務時有可能會出現異常情況,EventBus同樣也是藉助於一個ExceptionHandler進行回撥處理的。

以上就是Java中,UncaughtExceptionHandler的使用例項的介紹啦,看完你都學會了嗎?