Gracefully handling Android app crashes

Mukesh Solanki
ProAndroidDev
Published in
2 min readApr 4, 2022

To have your app crash in the hands of the users is the ultimate failure for any developer. That naturally raises the question of how do we make our app 100% crash-free. Well, that’s what we will find out today. But before we begin I want to make it clear that we will be simply handling the crash and preventing our app from crashing by no means does that mean our app does not have a bug. No Crashes do not equal No Bugs.

Alright now for the fun part. We will start by creating an Interface to handle our crashes lets call it ExceptionListener.

In our application class, we will implement the ExceptionListener interface and put the code here to handle the crash and indicate to the user that something is wrong.

Now for the actual code that will catch our error. We will add the below method in the application class and call it in the onCreate of the application class. This method will simply set up a listener and call the uncaughtException method we created earlier.

Just in case you are wondering this is the complete application.

Note: In the implementation of the ExceptionListener.uncaughtException() is where you would put something like firebase in place and log the error so you can handle the errors better in the future version. This is by no means a fix to your crashes. This is simply a gracefully way to handle your errors.

Feel free to drop a comment or reach out to me on LinkedIn or Twitter.

Sign up to discover human stories that deepen your understanding of the world.

Published in ProAndroidDev

The latest posts from Android Professionals and Google Developer Experts.

Written by Mukesh Solanki

Converts coffee to code! Writes about software development, automation, android. Connect with me on https://www.mukeshsolanki.com

Responses (6)

What are your thoughts?

The loop are to detect if there are any ANRs. And the leak can be avoided by simply setting the uncaught exception handler to null in the listener to avoid leaks

--

Wouldn't it be safer to use a tool like Firebase crashlytics? Users will not see a crach now but still they have a bad experience. In my code all business logic is handled within the domain module, this one does have a try catch, for those crashes I report them as non fatal issues

--

Few questions: why do you need a handler and busy waiting infinity loop here? On top of that you'll potential leak your application class since you add it to the JVM uncaught exception handler which is supposed to live a bit longer than your application class?

--