1. 父线程无法通过try... catch 捕获到子线程的异常
2. 未捕获的子线程异常不会导致父线程中止,父线程无法感知到子线程的异常
3. 可以通过指定UncaughtExceptionHandler来捕获子线程的异常
4. UncaughtExceptionHandler运行在子线程中
示例如下:
public class TestMain {
public static void main(String[] args) {
Thread.setDefaultUncaughtExceptionHandler(new MyUnCaughtExceptionHandler());
try {
Integer.parseInt("101B");
} catch (Exception e) {
System.out.println("catch exception, e=" + e.getLocalizedMessage());
}
ExceptionThread thread = new ExceptionThread();
try {
thread.setName("testThread");
thread.start();
} catch (Exception e) {
System.out.println("catch exception, e=" + e.getLocalizedMessage());
}
System.out.println("after subthread exception throwed, thread=" + Thread.currentThread().getId());
}
static class ExceptionThread extends Thread{
@Override
public void run() {
System.out.println("ExceptionThread, threadid=" + Thread.currentThread().getId());
Integer.parseInt("101A");
}
}
static class MyUnCaughtExceptionHandler implements Thread.UncaughtExceptionHandler {
@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println("uncaughtException, e=" + e.getLocalizedMessage() + ", thread=" + Thread.currentThread().getId());
}
}
}
运行结果: