子執行緒 異常處理(通用)
阿新 • • 發佈:2019-01-29
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 publicvoid 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 implementsThread.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 }