Java捕获并处理线程失败抛出的异常

使用 UncaughtExceptionHandler

示例代码如下:

Thread.UncaughtExceptionHandler handler = new Thread.UncaughtExceptionHandler() {
public void uncaughtException(Thread th, Throwable ex) {
        System.out.println("Uncaught exception: " + ex);
    }
};
Thread thread = 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();
    }
};
thread.setUncaughtExceptionHandler(handler);
thread.start();
posted @ 2017-03-13 16:26  安果果  阅读(563)  评论(0编辑  收藏  举报