Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android Force Close 捕獲與排查:UncaughtExceptionHandler 實作

編輯:關於 Android 程式設計

Force Close 通常代表應用發生未攔截的異常,例如空指標、陣列越界或 API 呼叫順序錯誤。除了修正根本原因,也可以透過 UncaughtExceptionHandler 統一記錄與處理。

Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
    public void uncaughtException(Thread thread, Throwable throwable) {
        Log.e("tag", "uncaught", throwable);
        android.os.Process.killProcess(android.os.Process.myPid());
    }
});

若要在子線程攔截,也必須在該線程中設定 handler。注意 uncaughtException 的 Thread 參數代表發生異常的線程,不一定是註冊時的主線程。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved