首页 > 编程语言 > 详细

使用setUncaughtExceptionHandler在线程外面捕获异常

时间:2019-12-20 09:48:53      阅读:79      评论:0      收藏:0      [点我收藏+]
package com.dwz.concurrency.chapter11;
/**
 * Thread的run方法是不能throw出异常的,只能在日志或者console中打印出来
 */
public class ThreadException {
    private final static int A = 10;
    private final static int B = 0;
    
    public static void main(String[] args) {
        Thread t = new Thread(()->{
            try {
                Thread.sleep(5_000);
                int result = A/B;
                System.out.println(result);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        
        //该方法可以在线程外面捕获到异常
        t.setUncaughtExceptionHandler((thread, e)->{
            System.out.println(e);
            System.out.println(thread);
        });
        t.start();
    }
}

使用了setUncaughtExceptionHandler后会把异常处理交给setUncaughtExceptionHandler,线程里面的异常不再输出日志信息

使用setUncaughtExceptionHandler在线程外面捕获异常

原文:https://www.cnblogs.com/zheaven/p/12071458.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!