Java之UncaughtExceptionHandler

來源:互聯網
上載者:User

標籤:

概述:

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.