1. 程式人生 > >子執行緒 異常處理(通用)

子執行緒 異常處理(通用)

複製程式碼
 1 public class ChildThread implements Runnable {
 2     private static ChildThreadExceptionHandler exceptionHandler;
 3 
 4     static {
 5         exceptionHandler = new ChildThreadExceptionHandler();
 6         Thread.setDefaultUncaughtExceptionHandler(exceptionHandler);
 7     }
 8 
 9     public
void run() { 10 System.out.println("do something 1"); 11 exceptionMethod(); 12 System.out.println("do something 2"); 13 } 14 15 private void exceptionMethod() { 16 throw new RuntimeException("ChildThread exception"); 17 } 18 19 public static class ChildThreadExceptionHandler implements
Thread.UncaughtExceptionHandler { 20 public void uncaughtException(Thread t, Throwable e) { 21 System.out.println(String.format("handle exception in child thread. %s", e)); 22 } 23 } 24 }
複製程式碼