How to avoid Force Close Error in Android

All android developer must have faced force close issue while developing an application.
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.

package com.example.forceclose;

import java.io.PrintWriter;
import java.io.StringWriter;

import android.app.Activity;
import android.content.Intent;
import android.os.Build;

public class ExceptionHandler implements
        java.lang.Thread.UncaughtExceptionHandler {
    private final Activity myContext;
    private final String LINE_SEPARATOR = "\n";

    public ExceptionHandler(Activity context) {
        myContext = context;
    }

    public void uncaughtException(Thread thread, Throwable exception) {
        StringWriter stackTrace = new StringWriter();
        exception.printStackTrace(new PrintWriter(stackTrace));
        StringBuilder errorReport = new StringBuilder();
        errorReport.append("************ CAUSE OF ERROR ************\n\n");
        errorReport.append(stackTrace.toString());

        errorReport.append("\n************ DEVICE INFORMATION ***********\n");
        errorReport.append("Brand: ");
        errorReport.append(Build.BRAND);
        errorReport.append(LINE_SEPARATOR);
        errorReport.append("Device: ");
        errorReport.append(Build.DEVICE);
        errorReport.append(LINE_SEPARATOR);
        errorReport.append("Model: ");
        errorReport.append(Build.MODEL);
        errorReport.append(LINE_SEPARATOR);
        errorReport.append("Id: ");
        errorReport.append(Build.ID);
        errorReport.append(LINE_SEPARATOR);
        errorReport.append("Product: ");
        errorReport.append(Build.PRODUCT);
        errorReport.append(LINE_SEPARATOR);
        errorReport.append("\n************ FIRMWARE ************\n");
        errorReport.append("SDK: ");
        errorReport.append(Build.VERSION.SDK);
        errorReport.append(LINE_SEPARATOR);
        errorReport.append("Release: ");
        errorReport.append(Build.VERSION.RELEASE);
        errorReport.append(LINE_SEPARATOR);
        errorReport.append("Incremental: ");
        errorReport.append(Build.VERSION.INCREMENTAL);
        errorReport.append(LINE_SEPARATOR);

        Intent intent = new Intent(myContext, AnotherActivity.class);
        intent.putExtra("error", errorReport.toString());
        myContext.startActivity(intent);

        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(10);
    }

}

Above class will work as a listener for forced close error. 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. You can see that Intent and startActivity is used to start the new Activity whenever app crashes. So it will start the activity named CrashActivity whenever app get crashed.For now I have passed the stack trace as an intent’s extras.

Now because CrashActivity is a regualr Android Actitvity you can handle it in whatever way you want.

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 overriden onCreate method.

Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this));

Your Activity may look something like this…

public class ForceClose extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

       Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this));

        setContentView(R.layout.main);

        // Your mechanism is ready now.. In this activity from anywhere 
        // if you get force close error it will be redirected to the CrashActivity.
    }
}

Your output will look like this

device-2013-08-09-113535

Download the ForceClose source code. device-2013-08-09-113544

72 thoughts on “How to avoid Force Close Error in Android

  1. Hi,
    The attached Forclose.zip file is not found. can you please repost the same again !!!
    Im still unable to get a solution out of this explanation.
    Thanks in advance

  2. HI hardik I try to use this but it din’t helped much .
    I have three Activity .
    Activity A ,B,C
    A launch B B launch C all as start activity for result .
    My problem is when C throw Exception it kills all the three .
    I tried your solution but its just help for first time the activity C throws Exception . when I launch Activity C second time when it give Exception again start killing B and A .

  3. Hi hardik,
    Can you tell me how to integrate Push Notification and Pie Chart in android application. or any url for that through which i can understand easily…

  4. I’ve put this code in, and it works within a normal activity, but if a background service can’t stop (because a function that is being called within the service fails), this doesn’t catch that error and the app displays a ‘not responding’ system dialog – any ideas?

    1. Hi Buddy,

      Actually I havn’t tested for service. But I guess it should work cz Service is also like activity but without UI. Still I will try this case and will reply you soon.

      And Thanks for visiting my blog.

      1. It seems to catch the error, but doesnt load the crash activity.

        It does work tho in an activity that hasn’t started a service or is bound to one.

      1. Viljem,
        Tho above code you need to maintain in your app. So if you are making your own task manager and you have taken care of this error handling your app will catch the Force Close.

        And if we talk about the OS, it has also written same kind of code thats why it is capturing all errors and they are displaying one alert box after catching the error. Simple Concept 🙂

  5. hi hardik,
    I want to try your code exactly but what it is handling force close here, if it occurs can i still make application resume. so at least, other modules of application work well rather than redirecting application to crash activity? can I do that with uncaught exception handler? thanks.

    1. Yea you can resume the same Activity also.
      For that you need to sightly modify the code.

      To start any activity what you need is reference of .class file.

      So in Constructor of UncaughtExceptionHandler use Activity inplace of Context and in uncaughtException method, replace
      Intent intent = new Intent(myContext, CrashActivity.class);

      with

      Intent intent = new Intent(myContext, );

      Ask me again if its nt clear to you.

  6. I put it into my application and instead of exit I tried to show a Toast message.
    This is my code:
    public class ExceptionHandler implements java.lang.Thread.UncaughtExceptionHandler {
    private final Context myContext;

    public ExceptionHandler(Context context) {
    myContext = context;
    }

    public void uncaughtException(Thread thread, Throwable exception) {
    StringWriter stackTrace = new StringWriter();
    exception.printStackTrace(new PrintWriter(stackTrace));
    System.err.println(stackTrace);

    Toast.makeText(myContext,stackTrace.toString(),Toast.LENGTH_LONG).show();
    // Process.killProcess(Process.myPid());
    // System.exit(10);
    }
    }

    I intentionally threw an exception in one of my Activities where I set the the handler.
    However, the Toast is never shown (though it was hit by debug), instead the activity hangs (not responding) and after minutes, the OS tells me that my application hangs.
    What should I set?

    1. Try putting toast in a runnable which runs on ui Thread. The uncaughtException method is not running in UT Thread os may be displaying toast is creating problem.

    1. No Dear, as name itself says that its Uncaught Exception.

      So it will get triggered only when you forgot to catch any exception.

      1. Thanks for reply. If i remove all the exceptions that handler in my app, will it may cause any problem? I Search crash report library like bugsense which throws exception even though i handle exception in my app. Do you know how it works ?

        1. Yea the core logic of bugsense like lib is same. But to achieve that you need to extend this. I havent used that lib. But you can achieve that by designing some more handlers and interfaces.

          1. In some cases if app throws exception the app perform some specific action depends on the exception. So it is not possible to remove catch exception from my application.
            Any suggestion or reference or some demo to handle both exceptions.

            1. U can create BaseActivity inside u can implement listener, and in your catch u can cal some method of that listener. That way u can implement it.

              1. Thanks for reply. Now my requirement is to post exception detail on server, so for that i have create a thread and post data on server and in handler write below statements,

                android.os.Process.killProcess(android.os.Process.myPid());
                System.exit(10);

                my data posted successfully but it display blank screen.
                And in log,

                “Launch timeout has expired, giving up wake lock!”

                So how to go back to previous screen once my data posted?

                One more thing why you are passing 10 in System.exit(10) ?

                Thanks.

  7. Hi Hiren,
    System.exit(10), where 10 is any random integer number. In java 1-127 are user defined codes. And the reason its showing black screen is , I haven’t called setContentView() method and also not finishing the activity. Just remove that System.exit line and try putting finish() over there.

  8. this is so needed trick for all apps, i use it to collect logs and in another activity i let the user to choose send crash report. this code works well if there is one activity, but i have 3 activity, when the third getting crashed it closed and 2nd activity getting called, the 2nd getting crashed force close popup raise, pressing ok cause first activity getting called:) with a force close popup. so as it’s clear the whole app won’t close at first place. i read the comments and someone had the exact opposite problem as his whole app getting close. i want my whole app getting close. i called the code on my first activity. so what i can do?

  9. Hey Hardik,
    I am facing some odd issue here. when i try to write that thing to file it is getting 3 times.
    why i don’t know can you help me ?

    Thanks.

  10. Hi Mr.Hardik Trivedi.I am a bigener in android app development.I just visit your blog.It would be really helpful for me.I like it.I hope I ll be helped by everybody in this blog.

  11. Its a good solution for handling force close error.

    Can you have an example of login with facebook, Google and Instragram in android apps?

    I need it on urgent basis. I tried a lot but still unsuccessful to do it and I have to do it within deadline.

    Please provide me demo code of these functionality asap.

    I hope you will provide me positive reply.

    1. Hey for Google,Instagram and FB login example, I would suggest to download their samples and directly integrate them in project.

  12. Hi I want to show my own alerDialog when ever my App crashes, I tried your code but i shows me blank screen. What might be the problem? Please help

  13. Hi Hardik,
    I’m not getting the Trace at all, instead the app hangs and I’m getting ANR dialog. I have implemented like this
    super.onCreate(savedInstanceState);
    Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this));

    setContentView(R.layout.activity_main);

    container = ContainerHolderSingleton.getContainerHolder().getContainer();
    crash_txt= (Button) findViewById(R.id.crash_txt);
    crash_txt.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    crash_tv123.setText(“”);
    }
    }
    );

    Thanks 🙂

  14. Hi, Thank you for your code. It is very good. I need the following modification can u tell me how to do?. I am having 2 activities Activity A and Activity B. If i get any exception in Activity B, it has to show a alert message to user. when pressed ok in alert message, Activtiy B has to be finished and Activity A has to be loaded. Waiting for your reply

    1. Hey In ExceptionHandler we have context, you can pass context of Activity and from that context call finish() method after showing Toast.

  15. Hi Hardik,
    If i’m having multiple fragments in 1 activity and if an exception is occures in 1 of fragment then i want to call the last fragment with your code. how can i achive this…
    Thanks

  16. Hi Hardik,

    If i’m having only 1 activity and multiple fragments and all fragments independent each other if in between them app get crash then how can i call to crashed fragment again instead of calling main activity.?

    1. You need to maintain the tag of that fragment after replace call. On crash detection reload the fragment by tag.

  17. nice code ,just one question whats the point of the last two lines of code in the function uncaughtException : android.os.Process.killProcess(android.os.Process.myPid());
    System.exit(10);

    i mean i am start another activity before i reached them so whats the point of them ?

  18. Hi… Thanks for this very wonderfull code… Really help me as a beginner in android-java… Specially because I am using Android IDE(AIDE from PlayStore)…

    I browsed your page for some more tutorials and its limited, but all very helpfull…

    Can you make/post a Tutorial pertaining to Material Design for pre-lollipop?
    Specially the ripple animation and the Raised Buttons …
    I can’t seem to make my buttons look like the ones on Material Design page of google… I found one tutorial that uses cardview to make a button which looks like the button in material design..

    Thanks

  19. Hi.. Hardik, I followed your document and its working nice as expected. Whenever app got crashed i am getting black screen around 4-5 seconds, after that it will relaunch my app (expected behaviour for my app). Is there any way to reduce that black screen time or any styling like white theme or blue theme etc..?

  20. Thanks for nice post. In case of ANR, does the same exception handling mechanism can be used? please answer. I am trying to tap on OK button for system generated force close pop-up window. Any ideas on how to do this. Please answer.

    1. I haven not tried this with ANR but in case of ANR you can catch is inside InterruptedException . Ad the from this exception you capture the data.

  21. Hi Hardik

    Thanks for this post .I have checked with activity and it is working perfect , but it is not working with services can you please advise.

  22. THANKSSSSSSSSS YOU SAVE MY PROYECTTTTT WITH AWS WHEN I AM GOING TO SIGNOUT OF AWS COGNITO, THANKSSSSS (cognitoidentity)

    I CATCH THIS “SignInProviderResultAdapter.onCognitoError()
    com.amazonaws.services.cognitoidentity.model.NotAuthorizedException: Access to Identity ‘us-east-1:e5b5f0db-8b27-4b70-be96-882fbdb353a1’ is forbidden.”

    Thanks man! god bless you.

  23. Thanks for this solution! It works great, but I have the following problem: After CrashActivity is shown, I never can get out of it. If “back” is pressed, CrashActivity shows again. If “home” is pressed and I start my app again I can only see the CrashActivity. Any idea how I can get out of it? Thanks a lot for your answer!

Leave a comment