Mike76
Mike76

Reputation: 979

Confusion with e.printStackTrace() in Android

I read here that e.printStackTrace() should not be used to catch exceptions on android.

On another source I read that I should use Log.e() instead of e.printStackTrace():

... catch (Exception e) {
 Log.e(TAG, "Foo did not work", e);
}

Do I have to manually remove these calls in the release build? What is the best practice to trace exception logs in Android?

Upvotes: 3

Views: 2707

Answers (1)

Westranger
Westranger

Reputation: 1367

The main intent of catching exceptions, is of course handling an occuring problem and due to this your catch part should always handle the error in some way e.g. use default values for the things which did not work, or try something different.

Anyway, if you are planning to publish your app in the Google Play Store and if you want to log the exceptions and use them for debugging puropses, to further improve app you can use Google Analytics API part for handling exceptions. It also provides facilities for collecting stack traces. (this is an exmaple from the API pages)

// Using StandardExceptionParser to get an Exception description.
try {

  // Request some scores from the network.
  ArrayList<Integer> highScores = getHighScoresFromCloud();

} catch (IOException e) {
// Get tracker.
Tracker t = ((AnalyticsSampleApp) getActivity().getApplication()).getTracker(
    TrackerName.APP_TRACKER);

  t.send(new HitBuilders.ExceptionBuilder()
      .setDescription(
          new StandardExceptionParser(this, null)
              .getDescription(Thread.currentThread().getName(), e))
      .setFatal(false)
      .build()
  );

  ... // Display alert to user that high scores are currently unavailable.
}

Afterwards all tracked stracktraces will be display in the Google Developer Console in the tap of you app.

Crashed and ANR' in the Google Developer Console (picture taken from the web)

You can also add an Listener for catching unhandled exceptions. So whenever an exceptions occours which you did not expect whis handler will be invoked.

Thread.setDefaultUncaughtExceptionHandler(new MyReportHelper());

Of course you should always try to catch and handle all exceptions which you know of, this handler is only for emergencies. For more details how an handler could look like see here.

Upvotes: 2

Related Questions