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


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,线程里面的异常不再输出日志信息


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM