Is UncaughtExceptionHandler set application wide?

369 views Asked by At

I have set an UncaughtExceptionHandler, so that I can write out stack traces to disk when my app crashes. I set this handler like this:

if (!(Thread.getDefaultUncaughtExceptionHandler() instanceof CustomExceptionHandler)) {
         exceptionHandler = new CustomExceptionHandler(
                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString(),
                null, this);

     Thread.setDefaultUncaughtExceptionHandler(exceptionHandler);
}

where CustomExceptionHandler implements UncaughtExceptionHandler. I keep the instance in my Activity, so I can use it for some other functionality (deleting the stack traces, retrieving them, etc).

I call the above piece of code in the onCreate of my Activity, but it seems to only trigger the first time any Activity is run.

I see the Thread.setDefaultUncaughtExceptionHandler call is static though, does that mean I can only set that handler only once in my app? Or can I set it per thread?

2

There are 2 answers

0
Anton Potapov On

From docs

 * Sets the default uncaught exception handler. This handler is invoked in
 * case any Thread dies due to an unhandled exception.

Yep, this handler is global and you need to set it once per app

0
k3b On

Is UncaughtExceptionHandler set application wide?

Yes. If you set it in an activity and the activity is destroyed the handler code in the activity may not exist any more.

I have set the handler in the Application-onCreate (not in the Activity) so it works for all Activities that belong to the Application to write crash logs.

For details see How to change crash message in android(if possible)

Here is the gpl-v3+ code for my crashlogger that writes logcat entries to file.

It is initialized in Application.onCreate like this

public class AndroFotoFinderApp extends Application {
    private LogCat mCrashSaveToFile = null;

    @Override public void onCreate() {
        super.onCreate();

        mCrashSaveToFile = new LogCat(this, Global.LOG_CONTEXT, HugeImageLoader.LOG_TAG,
                PhotoViewAttacher.LOG_TAG, CupcakeGestureDetector.LOG_TAG,
                FotoLibGlobal.LOG_TAG, ThumbNailUtils.LOG_TAG, IMapView.LOGTAG,
                ExifInterface.LOG_TAG, ImageMetaReader.LOG_TAG);
    }
}

where the constants Global.LOG_CONTEXT, HugeImageLoader.LOG_TAG, ... are android logging tags of different moduls of my code use like this

Log.d(HugeImageLoader.LOG_TAG, "some log message from modul HugeImageLoader)