CoroutineExceptionHandler helps you catch errors in coroutines so your app doesn't crash unexpectedly.
CoroutineExceptionHandler in Kotlin
val handler = CoroutineExceptionHandler { context, exception -> // handle the exception here }
The handler is a lambda that receives the coroutine context and the exception.
You add this handler to a coroutine's context to catch uncaught exceptions.
val handler = CoroutineExceptionHandler { _, exception -> println("Caught $exception") } GlobalScope.launch(handler) { throw RuntimeException("Error!") }
val handler = CoroutineExceptionHandler { _, exception -> println("Logging error: ${exception.message}") } runBlocking { launch(handler) { throw IllegalStateException("Oops") } }
This program starts a coroutine that throws an exception. The CoroutineExceptionHandler catches it and prints a message. The program continues running after handling the error.
import kotlinx.coroutines.* fun main() = runBlocking { val handler = CoroutineExceptionHandler { _, exception -> println("Caught exception: ${exception.message}") } val job = launch(handler) { println("Coroutine started") throw ArithmeticException("Divide by zero") } job.join() println("Coroutine finished") }
CoroutineExceptionHandler only catches exceptions that are not handled inside the coroutine.
It works with launch coroutines but not with async coroutines because async exceptions must be handled when calling await().
CoroutineExceptionHandler catches uncaught exceptions in coroutines.
Use it to keep your app stable and handle errors gracefully.
Add it to coroutine context when launching coroutines.
Practice
CoroutineExceptionHandler in Kotlin coroutines?Solution
Step 1: Understand CoroutineExceptionHandler role
It is designed to catch exceptions that are not handled inside coroutines.Step 2: Compare with other coroutine features
Launching coroutines, cancelling, or delaying are different coroutine features, not related to exception handling.Final Answer:
To catch uncaught exceptions in coroutines and handle them -> Option DQuick Check:
CoroutineExceptionHandler catches exceptions = A [OK]
- Confusing CoroutineExceptionHandler with coroutine launch or delay
- Thinking it cancels coroutines instead of handling exceptions
- Assuming it handles exceptions inside try-catch blocks
CoroutineExceptionHandler in Kotlin?Solution
Step 1: Recall CoroutineExceptionHandler syntax
It takes a lambda with two parameters: CoroutineContext and Throwable.Step 2: Check options for correct lambda signature
val handler = CoroutineExceptionHandler { context, exception -> println(exception) } matches the correct syntax: { context, exception -> ... }.Final Answer:
val handler = CoroutineExceptionHandler { context, exception -> println(exception) } -> Option AQuick Check:
Correct lambda parameters = A [OK]
- Using only one parameter in lambda
- Passing parameters incorrectly with parentheses
- Confusing syntax with other coroutine builders
val handler = CoroutineExceptionHandler { _, exception -> println("Caught: ${exception.message}") }
GlobalScope.launch(handler) {
throw IllegalArgumentException("Invalid argument")
}
Thread.sleep(100)Solution
Step 1: Understand CoroutineExceptionHandler usage
The handler catches uncaught exceptions and prints the message.Step 2: Analyze the thrown exception message
The exception is IllegalArgumentException with message "Invalid argument".Final Answer:
Caught: Invalid argument -> Option BQuick Check:
Exception message printed = D [OK]
- Expecting program crash instead of caught exception
- Confusing exception object with its message
- Ignoring Thread.sleep needed for coroutine to run
CoroutineExceptionHandler:val handler = CoroutineExceptionHandler { context, exception ->
println("Error: ${exception.message}")
}
GlobalScope.launch {
throw RuntimeException("Failure")
}Solution
Step 1: Check how handler is used
The handler is defined but not passed to launch coroutine context.Step 2: Understand consequence
Without adding handler to launch, exceptions are uncaught and not handled by it.Final Answer:
CoroutineExceptionHandler is not added to coroutine context -> Option CQuick Check:
Handler must be in launch context = C [OK]
- Defining handler but forgetting to use it in launch
- Assuming handler works globally without context
- Misunderstanding lambda parameter names
CoroutineScope using a single CoroutineExceptionHandler. Which approach correctly applies the handler to all coroutines?Solution
Step 1: Understand CoroutineScope context inheritance
Coroutines inherit context from their CoroutineScope, including exception handlers.Step 2: Apply handler to CoroutineScope context
Adding CoroutineExceptionHandler to the scope ensures all launched coroutines use it automatically.Final Answer:
Add the CoroutineExceptionHandler to the CoroutineScope's context when creating it -> Option AQuick Check:
Handler in scope context applies to all coroutines = B [OK]
- Adding handler only to some coroutines
- Relying on try-catch inside coroutines instead
- Using global try-catch which doesn't catch coroutine exceptions
Ready to prove it?
Pass the test and this pattern moves unknown
