Ideal way to set global uncaught exception Handler in Android

Samuh picture Samuh · May 4, 2010 · Viewed 44.8k times · Source

I want to set a global uncaught exception handler for all the threads in my Android application. So, in my Application subclass I set an implementation of Thread.UncaughtExceptionHandler as default handler for uncaught exceptions.

Thread.setDefaultUncaughtExceptionHandler(
                new DefaultExceptionHandler(this));

In my implementation, I am trying to display an AlertDialog displaying appropriate exception message.

However, this doesn't seem to work. Whenever, an exception is thrown for any thread which goes un-handled, I get the stock, OS-default dialog ("Sorry!-Application-has-stopped-unexpectedly dialog").

What is the correct and ideal way to set a default handler for uncaught exceptions?

Answer

fadden picture fadden · May 4, 2010

That should be all you need to do. (Make sure you cause the process to halt afterward -- things could be in an uncertain state.)

The first thing to check is whether the Android handler is still getting called. It's possible that your version is being called but failing fatally and the system_server is showing a generic dialog when it sees the process crash.

Add some log messages at the top of your handler to see if it's getting there. Print the result from getDefaultUncaughtExceptionHandler and then throw an uncaught exception to cause a crash. Keep an eye on the logcat output to see what's going on.