📖 Scenario: You are building a simple Kotlin program that uses coroutines to perform tasks asynchronously. Sometimes, these tasks might fail with errors. You want to learn how to catch and handle these errors properly inside coroutines.
🎯 Goal: Learn how to write Kotlin coroutines that handle exceptions using try-catch blocks and coroutine builders.
📋 What You'll Learn
Create a coroutine that throws an exception
Add a variable to hold the error message
Use try-catch inside a coroutine to catch the exception
Print the caught error message
💡 Why This Matters
🌍 Real World
Handling errors in asynchronous tasks is important to keep apps stable and responsive.
💼 Career
Many Kotlin developers use coroutines for background work and must handle exceptions properly to avoid crashes.
Progress0 / 4 steps
1
Create a coroutine that throws an exception
Write a suspend function called riskyTask that throws an IllegalArgumentException with the message "Something went wrong".
Kotlin
Hint
Use throw IllegalArgumentException("Something went wrong") inside the suspend function.
2
Add a variable to hold the error message
Create a mutable variable called errorMessage of type String? and set it to null.
Kotlin
Hint
Use var errorMessage: String? = null to create the variable.
3
Use try-catch inside a coroutine to catch the exception
Write a runBlocking block. Inside it, call riskyTask() inside a try block. Catch IllegalArgumentException and set errorMessage to the exception's message.
It takes a lambda with two parameters: context and exception.
Step 2: Match correct syntax
val handler = CoroutineExceptionHandler { context, exception -> println(exception) } correctly uses the two parameters in the lambda. Other options miss parameters or have wrong syntax.
Final Answer:
val handler = CoroutineExceptionHandler { context, exception -> println(exception) } -> Option D
The handler catches exceptions thrown inside the launch coroutine and prints the message.
Step 2: Trace program output
The exception message "Invalid argument" is printed by the handler, then "Done" is printed after job.join().
Final Answer:
Caught: Invalid argument
Done -> Option A
Quick Check:
Exception caught by handler, then Done printed [OK]
Hint: ExceptionHandler prints message, then main continues [OK]
Common Mistakes:
Expecting uncaught exception crash
Missing that handler catches exception
Ignoring job.join() effect
4. Identify the error in this Kotlin coroutine exception handling code:
import kotlinx.coroutines.*
fun main() = runBlocking {
val handler = CoroutineExceptionHandler { _, exception ->
println("Error: ${exception.message}")
}
val job = async(handler) {
throw RuntimeException("Failure")
}
job.await()
}
medium
A. Missing try-catch block inside async coroutine
B. The handler lambda parameters are incorrect
C. CoroutineExceptionHandler does not catch exceptions from async coroutines
D. Using runBlocking incorrectly
Solution
Step 1: Understand exception handling difference between launch and async
Exceptions in async are propagated via the deferred result and must be caught by try-catch on await().
Step 2: Analyze why CoroutineExceptionHandler fails here
CoroutineExceptionHandler does not catch exceptions from async coroutines because they are deferred until await().
Final Answer:
CoroutineExceptionHandler does not catch exceptions from async coroutines -> Option C
Quick Check:
async exceptions need try-catch on await() [OK]
Hint: Use try-catch on await() for async exceptions [OK]
Common Mistakes:
Expecting CoroutineExceptionHandler to catch async exceptions
Ignoring need for try-catch on await()
Misunderstanding handler lambda parameters
5. You want to handle exceptions from multiple launch coroutines in a Kotlin app and log errors without stopping other coroutines. Which approach is best?
hard
A. Use async coroutines and catch exceptions on await()
B. Attach a shared CoroutineExceptionHandler to the parent scope and launch coroutines within it
C. Wrap each coroutine body in a try-catch block and ignore exceptions
D. Use SupervisorJob without any exception handling
Solution
Step 1: Understand exception handling for multiple launch coroutines
Using a shared CoroutineExceptionHandler on the parent scope catches exceptions from all child launch coroutines without cancelling siblings.
Step 2: Evaluate other options
Wrapping each coroutine in try-catch is verbose and error-prone; async with await is for deferred results; SupervisorJob alone does not handle exceptions or logging.
Final Answer:
Attach a shared CoroutineExceptionHandler to the parent scope and launch coroutines within it -> Option B
Quick Check:
Shared handler on parent scope manages launch exceptions [OK]
Hint: Use shared CoroutineExceptionHandler on parent for launch coroutines [OK]
Common Mistakes:
Ignoring shared handler benefits
Using async instead of launch for fire-and-forget
Not handling exceptions leads to crashes
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.