Crash handling and reporting
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.setDefaultUncaughtExceptionHandlerthat 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 reada.b.c(SourceFile). Crashlytics needs the matchingmapping.txt, uploaded by its Gradle plugin, to show real names. - Non-fatal logging with
recordExceptionshows 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.txtis 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.
ApplicationExitInfois 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.
| Concern | API / file | When |
|---|---|---|
| Fatal crash | Crashlytics' own handler, plus yours chained in front | Any uncaught exception on any thread |
| Non-fatal error | FirebaseCrashlytics.getInstance().recordException(e) | Caught exception, app keeps running |
| Context | setCustomKey, log, setUserId | Before a crash or non-fatal, attached to the next report |
| Readable traces | mapping.txt, uploaded by the Crashlytics Gradle plugin | Every obfuscated release build |
| Why the process died | ActivityManager.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.setDefaultUncaughtExceptionHandleris 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.killProcessorSystem.exitin your handler instead of chaining. The crash SDK never sees the exception, and the system does not record a normal crash. - Do not call
recordExceptionfor a fatal crash inside the handler. Crashlytics already records it as a crash;recordExceptionadds a second, non-fatal event. - Keep the handler tiny: no network calls, no disk-heavy work, no locks. Wrap your own part in
try/finallyso 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
CancellationExceptionin coroutinetry/catchblocks when logging non-fatals. Rethrow it; it is not an error. - Coroutines: an exception in
launchthat noCoroutineExceptionHandlerhandles 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 = falsein a build type'sfirebaseCrashlyticsblock 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_MEMORYand more) and, for ANRs, a trace viagetTraceInputStream(). 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")
}previousis captured before installing, and called infinally, so Crashlytics and the system still see every crash even ifsetCustomKeythrows.- The handler never calls
recordExceptionor kills the process; the previous handler does the recording and the exit. logNonFatalrethrowsCancellationException, so normal coroutine cancellation is never reported as an error.- With the Crashlytics plugin applied and
isMinifyEnabled = true, the release build uploadsmapping.txtfor 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
- To "show a friendly restart screen", a developer installed a default handler in
Application.onCreatethat started a restart activity and then calledProcess.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.
- Rewrote the handler to save the previous handler, set a custom key, and call the previous handler in
finally, with no kill and norecordException. - 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
ApplicationExitInfoforREASON_CRASHon the next launch and showing a short "something went wrong" message then.
- After setting
isMinifyEnabled = true, Crashlytics showed traces likea.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.
- Applied
com.google.firebase.crashlyticsin the app module and removed the override from CI, so each release build uploads its ownmapping.txt. - Archived
mapping.txtfrom every release build as a CI artifact, so the team could run R8'sretracelocally 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.killProcessorSystem.exitin 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
recordExceptiononly for caught exceptions. - Missing mapping uploads. Adding the Crashlytics SDK without the Crashlytics Gradle plugin, or disabling
mappingFileUploadEnabledin 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 callsrecordExceptionalso catchesCancellationException, 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
-
Add Firebase Crashlytics to your app: the
firebase-crashlyticsdependency through the Firebase BoM, and thecom.google.firebase.crashlyticsplugin in the app module. -
In
Application.onCreate, install a handler that savesThread.getDefaultUncaughtExceptionHandler(), sets one custom key intry, and calls the previous handler infinally. -
Add a
logNonFatal(throwable, screen)helper that rethrowsCancellationExceptionand otherwise callsrecordException. Use it in onecatchblock (a JSON parse or file read). -
In the
releasebuild type, setisMinifyEnabled = true. Build with./gradlew assembleReleaseand confirmapp/build/outputs/mapping/release/mapping.txtexists. -
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.