捕获线程中发生的异常

2018-11-01  本文已影响10人  BestbpF

简述

当线程中出现异常时,我们可以使用Thread自带的方法进行全局捕获

方法

        Thread t1 = new Thread(){
            @Override
            public void run() {
                Object a = null;
                a.toString();
            }
        };
        t1.setName("线程t1");
        t1.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread t, Throwable e) {
                System.out.println("线程:" + t.getName() + " 出现了异常:");
                e.printStackTrace();
            }
        });
        t1.start();
Thread
        .setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread t, Throwable e) {
                System.out.println("线程:" + t.getName() + " 出现了异常:");
                e.printStackTrace();

            }
        });

Thread t1 = new Thread(){
    @Override
    public void run() {
        Object a = null;
        a.toString();
    }
};
t1.setName("t1");
t1.start();

Thread t2 = new Thread(){
    @Override
    public void run() {
        Object a = null;
        a.toString();
    }
};
t2.setName("t2");
t2.start();
上一篇下一篇

猜你喜欢

热点阅读