Alan
Alan

Reputation: 9471

Android Intercept Unhandled Exceptions

So I want to intercept the unhandled exceptions and I am doing this by:

Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {

        @Override
        public void uncaughtException(Thread t, Throwable e) {

            //MY CUSTOM CODE TO SEND LOGS
            System.exit(2);

        }

    });

Is there anyway I can execute my custom code and then resume normal way it handles these exceptions? I believe I am getting some hanging issues since System.exit doesn't seem to be working reliably.

Upvotes: 1

Views: 1617

Answers (1)

Paul Woitaschek
Paul Woitaschek

Reputation: 6807

You have to get the default handler first. Then intercept and send the error too the handler. System.exit... is a bad idea.

So first you create a custom exceptionhandler like you did:

public class CustomExceptionHandler implements Thread.UncaughtExceptionHandler {

    private final Thread.UncaughtExceptionHandler defaultUEH;

    public CustomExceptionHandler(Thread.UncaughtExceptionHandler defaultUEH) {
            this.defaultUEH = defaultUEH;
    }
    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        String stackTrace = Log.getStackTraceString(ex);
        String time = new Date(System.currentTimeMillis()).toString();
        String message = ex.getMessage();

        // send logs...

        defaultUEH.uncaughtException(thread, ex);
    }
}

So basically in your onCreate method (best used in a custom Application class to have it fall all parts) set the default exception handler if not already set (check not needed in Application):

Thread.UncaughtExceptionHandler defaultUEH = Thread.getDefaultUncaughtExceptionHandler();

if (!(defaultUEH instanceof CustomExceptionHandler)) {
    Thread.setDefaultUncaughtExceptionHandler(new CustomExceptionHandler(defaultUEH));
}

I wrote it here (remove the BuildConfig.DEBUG check) implemented to directly start the email client. If there is no email client installed, you should catch the ActivityNotFoundException.

Upvotes: 2

Related Questions