Android Global Exception Handler

Background / Motivation

Sometimes it is quite useful to handle / catch exceptions in a central handler. Typical samples are:

  • Handle Authorization problems e.g. with your backend
  • Central dispatching of these error to an Exception Collector like Crashlytics (ur just send an email)
  • Just show a message dialog to the to the user

Implementation

Just creating an Exception is straight forward java.lang.Thread.UncaughtExceptionHandler. The little more tricky part is integrating it into an Android application. Two obvious ways we might choose from:

  • Attach the Exception Handler in the Application
    • Can’t open UI Dialogs or other Activities properly
    • Will be executed for any activity
  • Attach the Exception Handler in an Activity
    • May start other activities
    • Needs a Base class to be applied in an easy way to all activities

Exception as Application Handler

Typical here is to log the exception and later on send it to the backend, e.g. after the application was restarted.

This sample code just logs each exception into a file, which we can later on inspect and send to the backend if we like.

Exception Handler

Activation of the Exception Handler

We need now only to attach it once in our Application:

Enable the Android Application

And of course make sure it is attached in our AndroidManifest.xml.

Exception Handler in an Activity

Attaching an exception handler in the activity allows us to do a little more, most important here starting a different activity work — in the case of the ApplicationContext it would just hang.

Exception Handler

In this case we check the exceptions if we could gracefully handle them. If so the start the appropriate activity and could pass more informations to it if needed.

Activation of the Exception Handler

Now it gets a little more messy. As we need to activate / init this handler with an Activity we have to ensure that either in each Activity or we provide a base activity all other inherit from.

Sample Code on Github

Sample code on GitHub

 

Paul Sterl has written 17 articles

One thought on “Android Global Exception Handler

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">