Handling Errors with CoroutineExceptionHandler in Kotlin
📖 Scenario: You are building a simple Kotlin program that runs coroutines to perform tasks. Sometimes, these tasks can fail with errors. You want to catch these errors gracefully and print a message instead of crashing the program.
🎯 Goal: Learn how to use CoroutineExceptionHandler to catch exceptions in coroutines and handle them by printing a friendly error message.
📋 What You'll Learn
Create a coroutine scope with a CoroutineExceptionHandler
Launch a coroutine that throws an exception
Handle the exception using the CoroutineExceptionHandler
Print the error message from the handler
💡 Why This Matters
🌍 Real World
In real apps, coroutines often run background tasks like network calls. Handling errors with CoroutineExceptionHandler helps keep apps stable and user-friendly.
💼 Career
Understanding CoroutineExceptionHandler is important for Kotlin developers working on Android apps or backend services that use coroutines for concurrency.
Progress0 / 4 steps
1
Create a CoroutineExceptionHandler
Create a val called handler and assign it a CoroutineExceptionHandler that prints the message "Caught exception: " followed by the exception's message.
Kotlin
Hint
Use CoroutineExceptionHandler { _, exception -> } and inside the lambda, print the exception message.
2
Create a CoroutineScope with the handler
Create a val called scope and assign it a CoroutineScope using Dispatchers.Default combined with the handler.
Kotlin
Hint
Use CoroutineScope(Dispatchers.Default + handler) to combine dispatcher and handler.
3
Launch a coroutine that throws an exception
Use scope.launch to start a coroutine that immediately throws an IllegalArgumentException with the message "Something went wrong".
Kotlin
Hint
Inside scope.launch { }, throw the exception with the exact message.
4
Print the error message from the handler
Run the program and print the output. The program should print Caught exception: Something went wrong.
Kotlin
Hint
Run the program and check the console output matches exactly.
Practice
(1/5)
1. What is the main purpose of CoroutineExceptionHandler in Kotlin coroutines?
easy
A. To delay coroutine execution by a fixed time
B. To launch new coroutines in a specific thread
C. To cancel running coroutines immediately
D. To catch uncaught exceptions in coroutines and handle them
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 D
Quick Check:
CoroutineExceptionHandler catches exceptions = A [OK]
C. CoroutineExceptionHandler is not added to coroutine context
D. GlobalScope.launch cannot throw exceptions
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 C
Quick Check:
Handler must be in launch context = C [OK]
Hint: Always add handler to launch context: launch(handler) [OK]
Common Mistakes:
Defining handler but forgetting to use it in launch
Assuming handler works globally without context
Misunderstanding lambda parameter names
5. You want to handle exceptions from multiple coroutines launched in a CoroutineScope using a single CoroutineExceptionHandler. Which approach correctly applies the handler to all coroutines?
hard
A. Add the CoroutineExceptionHandler to the CoroutineScope's context when creating it
B. Add the handler only to the first coroutine launched
C. Wrap each coroutine's code in try-catch instead of using CoroutineExceptionHandler
D. Use a global try-catch block outside all coroutines