`
zzhonghe
  • 浏览: 243372 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

线程外捕获某个线程内异常的方法

    博客分类:
  • Java
阅读更多
由于线程本质的特性,我们并不能直接捕获从线程中逃逸的异常,一旦异常逃逸出run方法,那它就直接上控制台了。

    /*
     * 1.Thread的异常在Thread外面是捕获不到的
     */
    public static void testThreadException(){
        ExecutorService se=Executors.newCachedThreadPool();
        try{
            se.execute(new Runnable(){
                public void run() {
                    throw new RuntimeException("TestException");
                }
            });
        }catch(RuntimeException e){
            //下面这条语句是执行不到的
            System.out.println("Message: "+e.getMessage());
        }
    }


我们只有通过设定回调类,传入回调的方法,这样才能够实现在外部处理线程中的异常:

    /*
     * 为某个批次的线程设置异常捕获器,通过ThreadFactory完成
     */
    public static void testCaughtThreadException(){
        ExecutorService se=Executors.newCachedThreadPool(new ThreadFactory(){
            public Thread newThread(Runnable r) {
                Thread t=new Thread(r);
                t.setUncaughtExceptionHandler(new UncaughtExceptionHandler(){
                    public void uncaughtException(Thread t, Throwable e) {
                        e.printStackTrace();
                        System.out.println("caught by myself"+e.getMessage());
                    }});
                return t;
            }
        });
        se.execute(new Runnable(){
            public void run() {
                throw new RuntimeException("TestException");
            }
        });
    }
    
    /*
     * 设定静态的异常捕获器,为所有的Thread异常添加捕获机制
     */
    static{
        Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler(){
            public void uncaughtException(Thread t, Throwable e) {
                e.printStackTrace();
                System.out.println("caught by myself"+e.getMessage());
            }}
        );
    }
    public static void testCaughtAllThreadException(){
        ExecutorService se=Executors.newCachedThreadPool();
        se.execute(new Runnable(){
            public void run() {
                throw new RuntimeException("TestException");
            }
        });
    }
    
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics