How to avoid Force Close Error Dialog in Android

In this tutorial, we’ll use the Thread.UncaughtExceptionHandler to avoid force close error dialog in an Android app.


Theory on Application Crash Reports for Android (ACRA):

All android developer must have faced force close issue while developing an application. As soon as a thread terminates due to an uncaught exception, JVM will query the thread for its UncaughtExceptionHandler using Thread.getUncaughtExceptionHandler() and will invoke the handler’s uncaughtException method, passing the thread and the exception as arguments.

If the thread has not explicitly set UncaughtExceptionHandler, its ThreadGroup object will act as its UncaughtExceptionHandler and exhibit the default behaviour of dumping the stacktrace on the console.

Here is a method to catch that error and treat it elegantly. This will create an error page kind of mechanism in your android application. So whenever your application is crashed user will not able to see that irritating pop up dialog. Instead of that app will display a predefined view to the user.

To make such kind of mechanism we need to make one error handler and an Activity class which will gain the view whenever the app gets forced closed. Let’s add one UncaughtExceptionHandler implementation to catch any unchecked exception during runtime.

Above class will work as a listener for forced close error. Now try to get some details about the exception and device info.

We will have a full error log plus device information too. Sometimes it also happens that particular error is coming from some specific manufacturer’s device. Now start the activity named CrashRepostActivity whenever app get crashed with stack trace as an intent’s extras.

Now comes the important part i.e. How to catch that exception. Though it is very simple. Copy following line of code in your each Activity just after the call of super method in your onCreate method or Implement a BaseActivity for all your activities or use in Application, which ever you preferred.

For this sample, I’ve created BaseActivity and it may look something like below.


New ACRA Design:

At this point, most of the developers tries to show some dialog or popups or even toast to the end users, but we have another plan. Lets us design an activity with elegant design.



Now we let the user to decide on whether to restart an application or reporting to developers about the issue.

Source Code:

Complete Source Code available at here.

I hope you will like the article and it will definitely help you to make your apps more productive. In case of any confusion or query, feel free to ask. And if you found this tutorial to be useful, Share with others.



About Durga Chiranjeevi

I’m a normal guy, engineer by education who is passionate about Programming and Internet. An android enthusiast, now moving for cross platforms and game development.