如何在主线程捕获子线程的异常 发表于 2020-07-17 | 分类于 并发编程 | 字数统计: 116 | 阅读时长 ≈ 1 [TOC] 通过对线程调用setUncaughtExceptionHandler,对处理器实现Thread.UncaughtExceptionHandler的接口 1234567891011121314151617181920212223242526272829303132333435class 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(); } }