如Java中另一个线程抛出的异常

可以使用公共静态接口Thread.UncaughtExceptionHandler完成。

Thread.UncaughtExceptionHandler是当线程因未捕获的异常而突然终止时调用的处理程序接口。

当一个线程由于未捕获的异常而即将终止时,Java虚拟机将使用它来 查询线程的 UncaughtExceptionHandler  Thread.getUncaughtExceptionHandler(),并将调用该处理程序的 uncaughtException方法,并将该线程和异常作为参数传递。如果某个线程没有 显式设置其UncaughtExceptionHandler,则其ThreadGroup对象将充当其 UncaughtExceptionHandler。如果ThreadGroup对象没有处理异常的特殊要求,它可以将调用转发到默认的未捕获异常处理程序

一个简单的例子:

package com.vista;

/**
 * Created by VISTA on 2018/12/28.
 * Java中如何捕获另一个线程抛出的异常?
 * 如下是示例
 */
public class CatchAnExecptionThrownByAnotherThread {

    public static void main(String[] args) {
        // create our uncaught exception handler
        Thread.UncaughtExceptionHandler handler = new Thread.UncaughtExceptionHandler() {
            public void uncaughtException(Thread th, Throwable ex) {
                System.out.println("Uncaught exception: " + ex);
            }
        };

// create another thread
        Thread otherThread = new Thread() {
            public void run() {
                System.out.println("Sleeping ...");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    System.out.println("Interrupted.");
                }
                System.out.println("Throwing exception ...");
                throw new RuntimeException();//主动抛出异常
            }
        };

// set our uncaught exception handler as the one to be used when the new thread
// throws an uncaught exception
        otherThread.setUncaughtExceptionHandler(handler);

// start the other thread - our uncaught exception handler will be invoked when
// the other thread throws an uncaught exception
        otherThread.start();
    }
}

 

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐