线程使用--使用setUncaughtExceptionHandler方法注册Runtime异常的处理者

Java多线程

1、不允许抛出受检异常,所以必须自己处理受检异常。

2、但是RuntimeException不可避免,抛出该异常时子线程会结束,但是主线程不会知道,因为主线程通过try catch无法捕获子线程异常

代码:

package com.csdn.test.threadmgr;

public class TestUncatchException
{
    public static class TestRuntimeExceptionThread extends Thread
    {
        public TestRuntimeExceptionThread()
        {
            super.setName("thread-TestRuntimeExceptionThread");
        }
        
        @Override
        public void run()
        {
            throw new RuntimeException("run time exception");
        }
    }

    public static void main(String[] args)
    {
        try
        {
            Thread test = new TestRuntimeExceptionThread();
            // 设置线程默认的异常捕获方法
            // test.setUncaughtExceptionHandler((Thread t, Throwable e) -> {System.out.println(t.getName() + ": " + e.getMessage());});
            test.start();
        }
        catch(Exception e)
        {
            System.out.println("catch thread exception");
        }
    }

}

输出:

Exception in thread "thread-TestRuntimeExceptionThread" java.lang.RuntimeException: run time exception
    at com.csdn.test.threadmgr.TestUncatchException$TestRuntimeExceptionThread.run(TestUncatchException.java:15)

 

解决方案:

Thread对象提供了setUncaughtExceptionHandler方法用来获取线程中产生的异常。而且建议使用该方法为线程设置异常捕获方法。

代码:

package com.csdn.test.threadmgr;

public class TestUncatchException
{
    public static class TestRuntimeExceptionThread extends Thread
    {
        // 指定线程名称 便于问题定位
        public TestRuntimeExceptionThread()
        {
            super.setName("thread-TestRuntimeExceptionThread");
        }
        
        @Override
        public void run()
        {
            throw new RuntimeException("run time exception");
        }
    }

    public static void main(String[] args)
    {
        Thread test = new TestRuntimeExceptionThread();
        // 设置线程默认的异常捕获方法
        test.setUncaughtExceptionHandler((Thread t, Throwable e) -> {
            System.out.println(t.getName() + ": " + e.getMessage());
        });
        test.start();
    }

}

输出:

thread-TestRuntimeExceptionThread: run time exception

 

参考博客:

https://blog.csdn.net/u013256816/article/details/50417822

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值