如何捕获线程运行期间的异常

import java.util.concurrent.TimeUnit;

public class ThreadException {

    public static void main(String[] args) {
        Thread t = new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(3);
                int res = 1/0;
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "error");

        t.setUncaughtExceptionHandler((thread, e)->{
            System.out.println(e);
            System.out.println(thread);
        });

        t.start();
    }
}

 

输出结果:

 

posted @ 2019-04-22 17:57  开嘴的板栗  阅读(283)  评论(0编辑  收藏  举报