setUncaughtExceptionHandler捕获异常线程

线程中的异常有点特殊。直接加try catch是捕获不到的。因为try catch的当前线程是main线程。 异常是在线程里面发生的,不属于main线程。

直接用try catch捕获不到异常:

public class ThreadExceptionDemo implements Runnable{
    @Override
    public void run() {
        System.out.println(0/0);
    }

    public static void main(String[] args) {
        Thread thread = new Thread(new ThreadExceptionDemo());
        try {
            thread.start();
        }catch (Exception e){
            System.out.println("线程异常了");
        }
    }
}

使用thread.setUncaughtExceptionHandler可以捕获到异常:

public class ThreadExceptionDemo implements Runnable{
    @Override
    public void run() {
        System.out.println(0/0);
    }

    public static void main(String[] args) {
        Thread thread = new Thread(new ThreadExceptionDemo());
        //自定义未捕获异常
        thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread t, Throwable e) {
                System.out.println("线程异常了!");
            }
        });
        thread.start();
    }
}

至于线程池的异常异常处理,这里先不讲。

发布了422 篇原创文章 · 获赞 7 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/enthan809882/article/details/104191645