Search...

Sunday, November 13, 2011

How to catch global exception using Thread.UncaughtExceptionHandler interface


Step1 : create a class which implements Thread.UncaughtExceptionHandler
e.g: public class GlobalExceptionHandler implements
Thread.UncaughtExceptionHandler{
     
      public void uncaughtException(Thread thread, Throwable ex) {

            Log.d("GLOBAL EXCEPTION", "Exception :" + ex.toString()
                        + " and Message:" + ex.getMessage());
           
            ex.printStackTrace();

           
           

      }
     

}

Step2: Create a class which implements Application interface.
e.g: public class MyApplication extends Application.
      public MyApplication() {
            Thread.setDefaultUncaughtExceptionHandler(new             GlobalExceptionHandler());
       
      }
}

Step3: Update your AndroidManifest.xml with your application class.
e.g: <application android:label="MyProject" android:name="MyApplication">


So in this way all the unhandled exception will be caught by your GlobalExceptionHandler class.

1 comment:

  1. It is very important that you re-throw the Uncaught exception handler once you have caught it. Otherwise your device will hang until a restart.

    ReplyDelete