Java如何捕获处理线程运行期间的非受检异常

我们在重写Thread的run()方法时,是被限制无法向上抛出异常的,而且java区分受检异常(checked exception)和非受检异常(unchecked exception),可能出现受检异常的代码,编译器会强制要求我们通过try/catch的方式进行异常处理。但是非受检异常不会被强制要求处理,如果我们想在线程里处理非受检异常,那么就需要使用Thread提供的UncaughtExceptionHandler

使用方式如下:

package com.thread.demo.unit3;

/**
 * @Author: Peacock__
 * @Date: 2019/5/6 16:19
 */
public class ThreadExceptionDemo {

    private static final int A = 10;
    private static final int B = 0;

    public static void main(String[] args) {
        Thread t = new Thread(() -> {
            try {
                //休息5秒
                Thread.sleep(5_000);
                //制造ArithmeticException异常(非受检)
                int result = A/B;
                System.out.println(result);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        //设置UncaughtExceptionHandler
        t.setUncaughtExceptionHandler(new MyExceptionHandler());

        t.start();

    }

    static class MyExceptionHandler implements Thread.UncaughtExceptionHandler {

        /**
         * Method invoked when the given thread terminates due to the
         * given uncaught exception.
         * <p>Any exception thrown by this method will be ignored by the
         * Java Virtual Machine.
         *
         * @param t the thread
         * @param e the exception
         */
        @Override
        public void uncaughtException(Thread t, Throwable e) {
            //处理非受检异常
            System.out.println("线程名称:"+t);
            System.out.println("异常描述:"+e);
        }
    }
}

如果我们不设置UncaughtExceptionHandler,控制台执行到int result = A/B;时会在控制台打印异常信息。

设置UncaughtExceptionHandler后,控制台输出如下:

线程名称:Thread[Thread-0,5,main]
异常描述:java.lang.ArithmeticException: / by zero

Process finished with exit code 0

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值