java基础-并发-如何捕获线程异常

本文介绍了一种在Java中捕获线程未捕获异常的方法。通过自定义线程异常处理器并结合线程工厂使用,可以有效地捕获并处理线程中抛出的异常。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

由于线程本质特性,使得我们不能捕获从线程中逃逸的异常。一旦异常逃出线程的run方法,他就会向外传播到控制台。
捕获线程中异常分为以下几步:
新建线程异常处理器,实现Thread.UncaughtExceptionHandler接口

class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler{
    @Override
    public void uncaughtException(Thread t, Throwable e) {
        System.out.println("catch " + e);
    }
}

创建线程工厂,给每一个由此工厂生产的线程都设置线程处理器:

class HandlerThreadFactory implements ThreadFactory{
    @Override
    public Thread newThread(Runnable r) {
        System.out.println(this+" creating new Thread");
        Thread t  = new Thread(r);
        System.out.println(" created " + t);
        //设置线程处理器
        t.setUncaughtExceptionHandler(new MyUncaughtExceptionHandler());
        System.out.println("eh= "+t.getUncaughtExceptionHandler());
        return t;
    }
}

创建线程:

class ExceptionThread implements Runnable{
    @Override
    public void run() {
        Thread t = Thread.currentThread();
        System.out.println("run() by "+ t);
        System.out.println("eh= " +t.getUncaughtExceptionHandler());
        throw new RuntimeException();
    }
}

使用测试:

public class CaptureUnCaughtException {
    public static void main(String[] args) {
        ExecutorService exec = Executors.newCachedThreadPool(new HandlerThreadFactory());
        exec.execute(new ExceptionThread());
    }
}

输出(不一定完全一样):

com.len.javabase.supervene.base.HandlerThreadFactory@4e25154f creating new Thread
 created Thread[Thread-0,5,main]
eh= com.len.javabase.supervene.base.MyUncaughtExceptionHandler@70dea4e
run() by Thread[Thread-0,5,main]
eh= com.len.javabase.supervene.base.MyUncaughtExceptionHandler@70dea4e
com.len.javabase.supervene.base.HandlerThreadFactory@4e25154f creating new Thread
 created Thread[Thread-1,5,main]
eh= com.len.javabase.supervene.base.MyUncaughtExceptionHandler@471be934
catch java.lang.RuntimeException
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值