CoroutineExceptionHandler: Global Uncaught Handler
Install a CoroutineExceptionHandler to log or recover from unhandled exceptions.
CoroutineExceptionHandler: Global Uncaught Handler is a free Kotlin Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Kotlin Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
What Is CoroutineExceptionHandler?
CoroutineExceptionHandler is a context element that handles uncaught exceptions from coroutines that do not have a catch handler. It acts as a last resort.
import kotlinx.coroutines.*
val handler = CoroutineExceptionHandler { context, exception ->
println("Caught unhandled: ${exception.message}")
}
fun main() = runBlocking {
val scope = CoroutineScope(Dispatchers.Default + handler)
scope.launch { throw RuntimeException("oops") }
delay(100)
}Only for Root Coroutines
CoroutineExceptionHandler only catches exceptions from root coroutines (launched directly on a scope). Child coroutines propagate to their parent, not the handler.
import kotlinx.coroutines.*
val handler = CoroutineExceptionHandler { _, e -> println("Handler: ${e.message}") }
fun main() = runBlocking {
// Root coroutine — handler fires:
CoroutineScope(handler).launch {
throw RuntimeException("root error")
}
delay(100)
// NOT handler (child of coroutineScope):
// launch { launch { throw RuntimeException() } }
}Does Not Suppress the Exception
The handler is invoked after the exception has already cancelled the coroutine. It is for logging, crash reporting, or cleanup — not for resuming execution.
import kotlinx.coroutines.*
val handler = CoroutineExceptionHandler { _, e ->
println("[CrashReport] ${e::class.simpleName}: ${e.message}")
// send to Crashlytics, Sentry, etc.
}
fun main() = runBlocking {
CoroutineScope(SupervisorJob() + handler).apply {
launch { throw IllegalStateException("state error") }
launch { delay(100); println("still alive") }
delay(200)
cancel()
}
}Handler + SupervisorJob
The combination of SupervisorJob + CoroutineExceptionHandler is the standard pattern for long-lived scopes: children fail independently, and unhandled failures are logged.
import kotlinx.coroutines.*
class AppScope {
private val handler = CoroutineExceptionHandler { _, e ->
println("Uncaught: ${e.message}")
}
val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default + handler)
}
fun main() = runBlocking {
val app = AppScope()
app.scope.launch { throw RuntimeException("task failed") }
app.scope.launch { delay(100); println("other task ok") }
delay(200)
app.scope.cancel()
}Handler with async
For async, exceptions are stored in the Deferred and thrown at await(). The handler does NOT fire for async unless the deferred is not awaited.
import kotlinx.coroutines.*
val handler = CoroutineExceptionHandler { _, e -> println("Handler: ${e.message}") }
fun main() = runBlocking {
val scope = CoroutineScope(SupervisorJob() + handler)
val deferred = scope.async { throw RuntimeException("async error") }
try {
deferred.await() // exception thrown here
} catch (e: RuntimeException) {
println("Caught from await: ${e.message}")
}
delay(50)
scope.cancel()
}Thread.UncaughtExceptionHandler Comparison
Unlike Java's UncaughtExceptionHandler, Kotlin's handler is part of the coroutine context and only applies within that scope's coroutines.
import kotlinx.coroutines.*
// Java style (applies to threads):
Thread.setDefaultUncaughtExceptionHandler { t, e ->
println("Thread ${t.name} threw: ${e.message}")
}
// Kotlin coroutine style (applies to coroutines in scope):
val handler = CoroutineExceptionHandler { _, e ->
println("Coroutine threw: ${e.message}")
}
fun main() = runBlocking { println("Handlers target different concurrency models") }Logging Pattern with MDC
In server apps, the handler can capture coroutine context information (like request IDs) for structured logging before forwarding to the logging framework.
import kotlinx.coroutines.*
val handler = CoroutineExceptionHandler { ctx, e ->
val jobName = ctx[CoroutineName]?.name ?: "unknown"
println("[${jobName}] ERROR: ${e.message}")
}
fun main() = runBlocking {
CoroutineScope(SupervisorJob() + handler).launch(CoroutineName("DataLoader")) {
throw RuntimeException("fetch failed")
}
delay(100)
}Crash Reporting Integration
Use the handler to forward uncaught exceptions to crash reporting services like Firebase Crashlytics or Sentry.
import kotlinx.coroutines.*
object CrashReporter {
fun record(e: Throwable) = println("[Crashlytics] ${e.message}")
}
val handler = CoroutineExceptionHandler { _, e ->
if (e !is CancellationException) CrashReporter.record(e)
}
val appScope = CoroutineScope(SupervisorJob() + Dispatchers.Default + handler)
fun main() = runBlocking {
appScope.launch { throw RuntimeException("unhandled in production") }
delay(100)
appScope.cancel()
}Handler Inheritance
The handler from the parent context is NOT automatically inherited by child coroutines. It must be in the root coroutine's context to fire.
import kotlinx.coroutines.*
val handler = CoroutineExceptionHandler { _, e -> println("Handler: ${e.message}") }
fun main() = runBlocking {
// Handler only fires at root level:
CoroutineScope(SupervisorJob() + handler).launch {
// Child of root — exception propagates to root handler:
launch { throw RuntimeException("nested") }
}
delay(100)
}Best Practice Summary
Always install a CoroutineExceptionHandler on your app-level or feature-level scopes. Log every non-cancellation exception. Never rely on it for control flow — it is observability only.
import kotlinx.coroutines.*
val globalHandler = CoroutineExceptionHandler { ctx, e ->
if (e !is CancellationException) {
println("[ERROR] ${ctx[CoroutineName]?.name}: ${e.message}")
}
}
val appScope = CoroutineScope(SupervisorJob() + Dispatchers.Default + globalHandler)
fun main() = runBlocking {
appScope.launch(CoroutineName("Auth")) { throw RuntimeException("token expired") }
delay(100); appScope.cancel()
}Quick Check
For which coroutine type does CoroutineExceptionHandler NOT automatically fire?
Recap
CoroutineExceptionHandler is a last-resort observer for uncaught exceptions in root coroutines. Combine with SupervisorJob for long-lived scopes. Use it for logging and crash reporting — never for control flow.
Frequently asked questions
Is the “CoroutineExceptionHandler: Global Uncaught Handler” lesson free?
Yes — the full text of “CoroutineExceptionHandler: Global Uncaught Handler” is free to read here on the web, and the Kotlin Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Kotlin Academy course, upgrade to CoddyKit PRO.
What will I learn in “CoroutineExceptionHandler: Global Uncaught Handler”?
Install a CoroutineExceptionHandler to log or recover from unhandled exceptions. You practise Kotlin Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Kotlin Academy?
No prior experience is required. Kotlin Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “CoroutineExceptionHandler: Global Uncaught Handler” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Kotlin Academy lesson?
Yes. Every Kotlin Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- SupervisorJob vs Job: Failure Isolation
- CoroutineExceptionHandler: Global Uncaught Handler
- async/await Exception Propagation
- Designing Resilient Coroutine Architectures