標籤:
概述:
UncaughtExceptionHandler是為了捕獲沒有被捕獲的異常,包括運行時異常,執行錯誤(記憶體溢出等),子線程拋出的異常等,你可以在uncaughtException(xx)裡對後續做處理包括資源釋放等
用法:
Runnable實現:
class YourRunable implements Runnable { public void run() { throw new RuntimeException("YourRunable"); }}
UncaughtExceptionHandler實現:
class YourUncaughtExceptionHandler implements UncaughtExceptionHandler { public void uncaughtException(Thread t, Throwable e) { System.out.println(t.getName()); System.out.println("*****************"); }}
測試代碼:
public static void main(String[] args) { Thread.setDefaultUncaughtExceptionHandler(new YourUncaughtExceptionHandler()); try { Thread yourThread = new Thread(new YourRunable()); yourThread.start(); } catch (Exception e) { e.printStackTrace(); } try { throw new RuntimeException("main"); } catch (Exception e) { e.printStackTrace(); } throw new RuntimeException("main end");}
輸出:
Thread-0*****************java.lang.RuntimeException: main at org.apache.tools.onest.crawler.nun.TestUncaughtExceptionHandler.main(TestUncaughtExceptionHandler.java:20)main*****************
結論:
1.已經被捕獲的異常不會被Handler
2.主線程通過Handler來操作子線程產生的異常,而不能直接try catch
3.主線程未被捕獲的異常可以在此被Handler
ps:
主線程擷取子線程的方式還可以通過子線程的標記位形式來操作,如封裝異常類等
本文轉自:http://snv.iteye.com/blog/2008487
Java之UncaughtExceptionHandler