Global Exception handling in Android

To be able to catch any exception you may encounter that isn’t part of a try-catch-clause, you can use the¬†Thread.setDefaultUncaughtExceptionHandler( Thread. UncaughtExceptionHandler ) method.

In the handler you can then perform whatever action you want. Don’t forget to call “System.exit()” though,¬†because otherwise this won’t work!

A simple example:

  1. public class SomeActivity extends Activity {
  2.  
  3.     private static final String LOG_TAG = "SomeActivity";
  4.  
  5.     @Override
  6.     protected void onCreate(Bundle savedInstanceState) {
  7.         super.onCreate(savedInstanceState);
  8.         Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
  9.             @Override
  10.             public void uncaughtException(Thread paramThread, Throwable paramThrowable) {
  11.                 Log.e(LOG_TAG, "OMG! Uncaught Exception!");
  12.                 // Without calling System.exit() this will not work.
  13.                 System.exit(2);
  14.             }
  15.         });
  16.     }
  17. }

For some more details have a look at “Using Global Exception Handling on android” on StackOverflow.com.

2 thoughts on “Global Exception handling in Android

Leave a Reply

Your email address will not be published. Required fields are marked *