標籤:
線程捕獲異常:
情況下,我們在main()方法裡是捕捉不到線程的異常的,比例如以下面代碼:
public class ExceptionThread implements Runnable{ @Override public void run() { throw new NullPointerException(); } public static void main(String[] args) { ExecutorService executorService = Executors.newCachedThreadPool(); try { System.out.println("運行線程"); executorService.execute(new ExceptionThread()); } catch (Exception e) { e.printStackTrace(); System.out.println("捕捉異常"); } }}上述代碼並不能在main方法裡捕捉線程異常,那麼我們怎麼才幹捕捉到線程的異常資訊呢?
以下我們看這段代碼
/** * 定義異常線程內容 */class MyExceptionThread implements Thread.UncaughtExceptionHandler { @Override public void uncaughtException(Thread t, Throwable e) { // 捕捉異常後的業務處理放在這裡 System.out.println("捕捉的異常資訊例如以下"); System.out.println(e); }}/** * 定義異常線程工廠 */class ExceptionThreadFactory implements ThreadFactory { @Override public Thread newThread(Runnable r) { Thread thread = new Thread(r); // 此處是捕捉異常的設定。 thread.setUncaughtExceptionHandler(new MyExceptionThread()); return thread; }}/** * 執行線程 */class ExceptionThread2 implements Runnable{ @Override public void run() { try { Thread.sleep(1000l); } catch (InterruptedException e) { e.printStackTrace(); } // 拋出異常 throw new NullPointerException(); } public static void main(String[] args) { // 通過我們自己寫的ExceptionThreadFactory線程工廠,構造線程池 ExecutorService executorService = Executors.newCachedThreadPool(new ExceptionThreadFactory()); try { System.out.println("執行線程"); // 啟動三個線程 executorService.execute(new ExceptionThread2()); executorService.execute(new ExceptionThread2()); executorService.execute(new ExceptionThread2()); } catch (Exception e) { e.printStackTrace(); System.out.println("捕捉異常"); } }}上面的輸出結果是
運行線程捕捉的異常資訊例如以下java.lang.NullPointerException捕捉的異常資訊例如以下java.lang.NullPointerException捕捉的異常資訊例如以下java.lang.NullPointerException
得出的結論是:main()該方法仍然沒有捕捉到異常的線程,當然,這個設定是合理的。現在每個線程都有自己的異常處理機制,怎麼辦呢,句子,建立一個線程時,該語句是好的~
收工。
Java線程學習筆記(兩) 線程異常處理