Java Thread.UncaughtExceptionHandler

如果在java中定义了如下的类,希望在多线程环境下,捕获异常

    static class myRun implements Runnable {
        @Override
        public void run() {
            System.out.println("myRun.run()");
            throw new RuntimeException();
        }
    }

那么通过如下两种方式,是不能在调用这两个线程的程序中,捕获到异常的。

         try {

         new Thread(new myRun()).start();

         } catch (Exception e) {
         // TODO: handle exception
         System.out.println("caught exception in main");
         }

        try {
            Executors.newCachedThreadPool().execute(new myRun());
        } catch (Exception e) {
            // TODO: handle exception
            System.out.println("caught exception in main");
        }

在Java中,如果要捕获线程中的异常,需要通过UncaughtExceptionHandler实现。

UncaughtExceptionHandler是一个接口,只有一个方法:

void uncaughtException(Thread t, Throwable e)
当给定线程因给定的未捕获异常而终止时,调用该方法。

所以,如果希望捕获线程的异常,我们可以实现UncaughtExceptionHandler:

    static class myUncaughtExceprionHandler implements UncaughtExceptionHandler {

        @Override
        public void uncaughtException(Thread t, Throwable e) {
            // TODO Auto-generated method stub
            System.out.println("caughtException in my handler");
            System.out.println(e);
        }

    }

然后,在线程开始之前,设置线程的uncaughtExceptionHandler:

         Thread thread = new Thread(new myRun());
         thread.setUncaughtExceptionHandler(new myUncaughtExceprionHandler());
         thread.start();

但是,在使用线程池的时候,问题来了,到底应该在哪设置uncaughtExceptionHandler?

这时候,需要自定义一个新的ThreadFactory:

    static class HandlerThreadFactory implements ThreadFactory {
        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setUncaughtExceptionHandler(new myUncaughtExceprionHandler());
            return t;
        }
    }

然后通过如下方式运行程序:

         ExecutorService exe = Executors.newCachedThreadPool(new
         HandlerThreadFactory());
         exe.execute(new myRun());
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值