线程使用--使用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

猜你喜欢

转载自blog.csdn.net/zangdaiyang1991/article/details/84304096