Android Thread.UncaughtExceptionHandler捕獲

來源:互聯網
上載者:User

標籤:

在Java 的異常處理機制中:
如果拋出的是Exception異常的話,必須有try..catch..進行處理,屬於checked exception。
如果拋出的是RuntimeException異常的話,則不是必須進行try..catch..異常處理,發生異常之後將由JVM進行處理,屬於unchecked exception。
注意:為了保證程式的健壯性,建議拋出RunntimeException異常,也使用try..catch..進行處理。

這兩者最本質的區別在於設計者認為使用者是否能夠並且應該處理這個異常。

Java 異常的分類:
基類為:Throwable
Error 和 Exception 繼承於Throwable
RuntimeException和IOException等繼承Exception
其中,Error和RuntimeException及其子類屬於unchecked exception, 而其他異常為checked exception。

Error類描述了Java運行系統中的內部錯誤以及資源耗盡的情形,應用程式不應該拋出這種類型的對象(一般是由Java虛擬機器拋出)。如果出現這種錯誤,除了儘力使程式安全退出外,在其他方面是無能為力的。所以,在我們在程式設計時,應該更關注Exception體系。

RuntimeExcption體系,包括錯誤的類型轉換,數組越界訪問和試圖訪問null 指標等等。如果出現RuntimeException,那麼一定是你自己的錯誤。

其他非RuntimeExcetpion(IOException等等),這類異常一般是外部錯誤,例如試圖從檔案尾後讀取資料等,這並不是程式本身的錯誤,而是在應用環境中出現的外部錯誤。

在Android開發中,常常會出現uncheched Exception 導致程式的crash,為了提供良好的使用者體驗,並對出錯的資訊進行收集,以便對程式進行改進,提高程式的健壯性。因此,常使用Thread.UncaughtExceptionHandler來進行處理。

首先需要繼承Thread.UncaughtExceptionHandler類

public class CrashHandler implements Thread.UncaughtExceptionHandler {    public static final String TAG = CrashHandler.class.getSimpleName();    private static CrashHandler INSTANCE = new CrashHandler();    private Context mContext;    private Thread.UncaughtExceptionHandler mDefaultHandler;    private CrashHandler() {    }    public static CrashHandler getInstance() {        return INSTANCE;    }    public void init(Context ctx) {        mContext = ctx;        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();        Thread.setDefaultUncaughtExceptionHandler(this);    }    @Override    public void uncaughtException(Thread thread, Throwable ex) {        // if (!handleException(ex) && mDefaultHandler != null) {        // mDefaultHandler.uncaughtException(thread, ex);        // } else {        // android.os.Process.killProcess(android.os.Process.myPid());        // System.exit(10);        // }        System.out.println("uncaughtException");        new Thread() {            @Override            public void run() {                Looper.prepare();                new AlertDialog.Builder(mContext).setTitle("提示").setCancelable(false)                        .setMessage("程式崩潰了...").setNeutralButton("我知道了", new OnClickListener() {                            @Override                            public void onClick(DialogInterface dialog, int which) {                                System.exit(0);                            }                        })                        .create().show();                Looper.loop();            }        }.start();    }    /**     * 自訂錯誤處理,收集錯誤資訊 發送錯誤報表等操作均在此完成. 開發人員可以根據自己的情況來自訂異常處理邏輯     *      * @param ex     * @return true:如果處理了該異常資訊;否則返回false     */    private boolean handleException(Throwable ex) {        if (ex == null) {            return true;        }        // new Handler(Looper.getMainLooper()).post(new Runnable() {        // @Override        // public void run() {        // new AlertDialog.Builder(mContext).setTitle("提示")        // .setMessage("程式崩潰了...").setNeutralButton("我知道了", null)        // .create().show();        // }        // });        return true;    }}

然後在Application類中進行註冊

public class MyApplication extends Application{    @Override    public void onCreate(){    super.onCreate();        initErrorHandler();    }   private void initErrorHandler(){    CrashHandler handler = CrashHandler.getInstance();    handler.init(this);   }}

 

 

本文轉自:http://blog.csdn.net/wangbole/article/details/8161524

Android Thread.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.