Crash handling and reporting

Learn Android crash reporting with Firebase Crashlytics: uncaught exception handlers that chain, non-fatal logging, ApplicationExitInfo, and R8 mapping uploads. About 25 minutes.

Why it matters

  • An uncaught exception on any thread kills the app process. Without crash reporting you only hear about it from reviews, with no stack trace.
  • A custom Thread.setDefaultUncaughtExceptionHandler that does not chain to the previous handler silently breaks Crashlytics (or the system crash dialog). Senior interviews probe exactly this.
  • With isMinifyEnabled = true, R8 renames classes and methods, so release stack traces read a.b.c(SourceFile). Crashlytics needs the matching mapping.txt, uploaded by its Gradle plugin, to show real names.
  • Non-fatal logging with recordException shows you caught errors (a failed parse, a bad cache entry) as trends before they turn into crashes or support tickets.

The simple explanation

  • A crash reporter is the flight recorder: it saves what happened in the last moments before the crash.
  • The uncaught exception handler is a chain of people passing a note: each one reads it, adds something, and must pass it on, or the people further down never see it.
  • mapping.txt is the codebook that turns the recorder's coded names back into real ones.
  • Non-fatal logging is the maintenance log: a flickering light noted today so it does not become a fire.
  • ApplicationExitInfo is the accident report written by the system, even when the recorder could not run.

How does crash reporting work on Android? When an exception escapes every try/catch on a thread, the runtime calls the process-wide default UncaughtExceptionHandler. Android's own handler logs the crash and kills the process. A crash SDK such as Firebase Crashlytics installs its handler when it initializes (before Application.onCreate with the default setup), writes the crash report to disk, then calls the handler that was installed before it. The report is sent on the next app launch.

If you add your own handler, follow the same contract: save the previous handler, do a small amount of work, then call the previous handler. Do not kill the process yourself and do not swallow the exception.

ConcernAPI / fileWhen
Fatal crashCrashlytics' own handler, plus yours chained in frontAny uncaught exception on any thread
Non-fatal errorFirebaseCrashlytics.getInstance().recordException(e)Caught exception, app keeps running
ContextsetCustomKey, log, setUserIdBefore a crash or non-fatal, attached to the next report
Readable tracesmapping.txt, uploaded by the Crashlytics Gradle pluginEvery obfuscated release build
Why the process diedActivityManager.getHistoricalProcessExitReasons (API 30+)Next launch; covers ANRs, native crashes, low-memory kills

Crashlytics shows obfuscated traces unless it has the mapping file for that exact build. The Crashlytics Gradle plugin (com.google.firebase.crashlytics) generates a mapping file ID, embeds it in the app and uploads mapping.txt automatically for variants that use R8 obfuscation. Play Console reads the mapping file from an app bundle automatically when you build with AGP 4.1 or newer.

Notes

  • Thread.setDefaultUncaughtExceptionHandler is process-wide: it handles uncaught exceptions on every thread that has no handler of its own.
  • Always read Thread.getDefaultUncaughtExceptionHandler() first and call it at the end of your handler. That previous handler is usually Crashlytics, which in turn calls the system handler that ends the process.
  • Do not call Process.killProcess or System.exit in your handler instead of chaining. The crash SDK never sees the exception, and the system does not record a normal crash.
  • Do not call recordException for a fatal crash inside the handler. Crashlytics already records it as a crash; recordException adds a second, non-fatal event.
  • Keep the handler tiny: no network calls, no disk-heavy work, no locks. Wrap your own part in try/finally so the previous handler is called even if your code throws.
  • recordException(e) logs a non-fatal; log(message) adds breadcrumbs; setCustomKey(key, value) tags state such as the current screen. Never put personal data in keys or logs.
  • Never swallow CancellationException in coroutine try/catch blocks when logging non-fatals. Rethrow it; it is not an error.
  • Coroutines: an exception in launch that no CoroutineExceptionHandler handles reaches the thread's uncaught exception handler, so it is reported as a crash.
  • The Crashlytics plugin uploads the mapping file during the release build. Set mappingFileUploadEnabled = false in a build type's firebaseCrashlytics block only where you do not want uploads, such as a local-only build type.
  • ApplicationExitInfo (API 30+) gives a reason (REASON_CRASH, REASON_ANR, REASON_CRASH_NATIVE, REASON_LOW_MEMORY and more) and, for ANRs, a trace via getTraceInputStream(). Read it off the main thread on the next start.
  • Test the setup in a release-like build: force a crash, relaunch the app (reports are sent on the next launch), and check that Crashlytics shows readable class names.

Code example

This shows a production-style handler that adds context and then chains to the previous handler, plus a helper for non-fatal errors. It is installed once in Application.onCreate, after Crashlytics has initialized.

// CrashReporting.kt
package com.example.app
 
import android.app.Application
import com.google.firebase.crashlytics.FirebaseCrashlytics
import kotlin.coroutines.cancellation.CancellationException
 
object CrashReporting {
    private val crashlytics get() = FirebaseCrashlytics.getInstance()
 
    fun install() {
        val previous = Thread.getDefaultUncaughtExceptionHandler()
        Thread.setDefaultUncaughtExceptionHandler { thread, throwable ->
            try {
                // Small, safe work only: context for the crash report.
                crashlytics.setCustomKey("crash_thread", thread.name)
            } finally {
                // Hand over to Crashlytics (and then the system), which records and ends the process.
                previous?.uncaughtException(thread, throwable)
            }
        }
    }
 
    fun logNonFatal(throwable: Throwable, screen: String) {
        if (throwable is CancellationException) throw throwable
        crashlytics.setCustomKey("screen", screen)
        crashlytics.recordException(throwable)
    }
}
 
class App : Application() {
    override fun onCreate() {
        super.onCreate()
        CrashReporting.install()
    }
}
// app/build.gradle.kts
plugins {
    id("com.android.application")
    id("com.google.gms.google-services")
    id("com.google.firebase.crashlytics")
}
 
android {
    buildTypes {
        release {
            isMinifyEnabled = true
            proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
        }
    }
}
 
dependencies {
    implementation(platform("com.google.firebase:firebase-bom:35.2.0")) // check for the current BoM
    implementation("com.google.firebase:firebase-crashlytics")
}
  • previous is captured before installing, and called in finally, so Crashlytics and the system still see every crash even if setCustomKey throws.
  • The handler never calls recordException or kills the process; the previous handler does the recording and the exit.
  • logNonFatal rethrows CancellationException, so normal coroutine cancellation is never reported as an error.
  • With the Crashlytics plugin applied and isMinifyEnabled = true, the release build uploads mapping.txt for that build automatically.

Run the idea in plain Kotlin

fun main() {
  val log = mutableListOf<String>()

  // Stands in for the system handler that ends the process.
  Thread.setDefaultUncaughtExceptionHandler { _, e ->
      log.add("system: process would end (" + e.message + ")")
  }

  // Stands in for a crash SDK: it saves the previous handler and chains to it.
  val beforeSdk = Thread.getDefaultUncaughtExceptionHandler()
  Thread.setDefaultUncaughtExceptionHandler { t, e ->
      log.add("crash sdk: report saved for " + t.name)
      beforeSdk?.uncaughtException(t, e)
  }

  // Your handler, installed last, also chains.
  val beforeApp = Thread.getDefaultUncaughtExceptionHandler()
  Thread.setDefaultUncaughtExceptionHandler { t, e ->
      try {
          log.add("app: added context for " + t.name)
      } finally {
          beforeApp?.uncaughtException(t, e)
      }
  }

  val worker = Thread({ throw IllegalStateException("disk full") }, "sync-worker")
  worker.start()
  worker.join()

  log.forEach { println(it) }
}

Expected output:

app: added context for sync-worker
crash sdk: report saved for sync-worker
system: process would end (disk full)

In production

Crashlytics went quiet after a new crash handler shipped
  • To "show a friendly restart screen", a developer installed a default handler in Application.onCreate that started a restart activity and then called Process.killProcess(Process.myPid()).
  • It never called the previous handler. Crashlytics' handler was never reached, so fatal crashes stopped appearing while users kept reporting the app closing.
  • A later attempt added recordException(throwable) before the kill, so crashes showed up only as non-fatals and the crash-free users metric looked better than reality.
The fix
  • Rewrote the handler to save the previous handler, set a custom key, and call the previous handler in finally, with no kill and no recordException.
  • Added a release-build smoke test to the release checklist: force a crash, relaunch, and confirm a fatal issue appears in Crashlytics with readable names.
  • Kept the friendly restart experience by checking ApplicationExitInfo for REASON_CRASH on the next launch and showing a short "something went wrong" message then.
Every release crash was unreadable after turning on minification
  • After setting isMinifyEnabled = true, Crashlytics showed traces like a.b.c(SourceFile) for every new crash.
  • The app module did not apply the Crashlytics Gradle plugin, only the SDK dependency, so no mapping file was ever uploaded.
  • CI built release bundles on a machine with mappingFileUploadEnabled = false, copied from a local-only config.
The fix
  • Applied com.google.firebase.crashlytics in the app module and removed the override from CI, so each release build uploads its own mapping.txt.
  • Archived mapping.txt from every release build as a CI artifact, so the team could run R8's retrace locally on traces from other sources.
  • Left the bundle upload to Play unchanged: Play Console already reads the mapping file from the app bundle.

Common mistakes

  • Not chaining to the previous handler. Replacing the default handler without calling the old one disables Crashlytics and the system crash handling. Save Thread.getDefaultUncaughtExceptionHandler() and call it last.
  • Killing the process yourself. Process.killProcess or System.exit in the handler skips the crash SDK and the system's normal crash record. Let the previous handler end the process.
  • Calling recordException for a fatal crash. In the handler it creates a duplicate non-fatal event; Crashlytics already records the crash. Use recordException only for caught exceptions.
  • Missing mapping uploads. Adding the Crashlytics SDK without the Crashlytics Gradle plugin, or disabling mappingFileUploadEnabled in CI, leaves every obfuscated trace unreadable.
  • Doing real work in the handler. Network calls, database writes or waiting on locks in a dying process can hang or throw. Add a custom key at most, then chain.
  • Reporting coroutine cancellation as an error. A catch (e: Exception) that calls recordException also catches CancellationException, which floods the dashboard and breaks cancellation. Rethrow it.

Interview questions

Answer out loud first. Then reveal the answer and compare it at each depth.

“How do you handle uncaught exceptions in an Android app?”

“What is the difference between a fatal crash and a non-fatal in Crashlytics?”

“Why do production stack traces show names like a.b.c, and how do you fix it?”

“How does ApplicationExitInfo help with crash analysis?”

Quiz

What must a custom default UncaughtExceptionHandler do so that Crashlytics still reports crashes?

Which Crashlytics call records a caught exception as a non-fatal event?

What gives Crashlytics readable stack traces for a minified release build?

Which API tells you on the next launch that the process died from an ANR or a low-memory kill (API 30+)?

0 of 4 answered

Mini task

15-minute exercise: Add chained crash handling

  1. Add Firebase Crashlytics to your app: the firebase-crashlytics dependency through the Firebase BoM, and the com.google.firebase.crashlytics plugin in the app module.

  2. In Application.onCreate, install a handler that saves Thread.getDefaultUncaughtExceptionHandler(), sets one custom key in try, and calls the previous handler in finally.

  3. Add a logNonFatal(throwable, screen) helper that rethrows CancellationException and otherwise calls recordException. Use it in one catch block (a JSON parse or file read).

  4. In the release build type, set isMinifyEnabled = true. Build with ./gradlew assembleRelease and confirm app/build/outputs/mapping/release/mapping.txt exists.

  5. Install the release build, trigger throw RuntimeException("test crash") from a debug-only button or hidden menu, relaunch the app, and check the Crashlytics dashboard. Remove the test crash afterwards.

Done when: Crashlytics shows exactly one fatal issue for the test crash, with readable class and method names and your custom key, and your non-fatal appears separately.

Next: R8, shrinking and obfuscation