如何在主线程捕获子线程的异常

[TOC]

通过对线程调用setUncaughtExceptionHandler,对处理器实现Thread.UncaughtExceptionHandler的接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

class test extends Thread{
public static class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {

public void uncaughtException(Thread t, Throwable e) {

System.out.println("MyUncaughtExceptionHandler do something...");

System.out.println("errorMsg:" + e.getMessage());

}

}
public static class ChildTask implements Runnable {

public void run() {

// Thread.currentThread().setUncaughtExceptionHandler(new MyUncaughtExceptionHandler());

System.out.println("do something");

throw new RuntimeException("ChildTask异常");

}

}
public static void main(String[] args) {


Thread t= new Thread(new ChildTask());
t.setUncaughtExceptionHandler(new MyUncaughtExceptionHandler());
t.start();

}
}