Bird
Raised Fist0
Kotlinprogramming~20 mins

Exception handling in coroutines in Kotlin - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Coroutine Exception Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of coroutine with try-catch
What is the output of this Kotlin coroutine code snippet?
Kotlin
import kotlinx.coroutines.*

fun main() = runBlocking {
    val job = launch {
        try {
            delay(100)
            throw IllegalArgumentException("Error in coroutine")
        } catch (e: IllegalArgumentException) {
            println("Caught: ${e.message}")
        }
    }
    job.join()
    println("Coroutine finished")
}
AException in thread "main" java.lang.IllegalArgumentException: Error in coroutine
B
Caught: Error in coroutine
Coroutine finished
CCaught: Error in coroutine
D
Coroutine finished
Caught: Error in coroutine
Attempts:
2 left
💡 Hint
Look at where the exception is caught inside the coroutine.
❓ Predict Output
intermediate
2:00remaining
Exception propagation in coroutine scope
What will be printed when this Kotlin code runs?
Kotlin
import kotlinx.coroutines.*

fun main() = runBlocking {
    val handler = CoroutineExceptionHandler { _, exception ->
        println("Handled: ${exception.message}")
    }
    val job = launch(handler) {
        throw ArithmeticException("Divide by zero")
    }
    job.join()
    println("End of main")
}
A
Handled: Divide by zero
End of main
BException in thread "main" java.lang.ArithmeticException: Divide by zero
C
End of main
Handled: Divide by zero
DEnd of main
Attempts:
2 left
💡 Hint
Check how CoroutineExceptionHandler works with launch.
🔧 Debug
advanced
2:00remaining
Why does this coroutine exception crash the program?
Consider this Kotlin code snippet. Why does the program crash with an unhandled exception?
Kotlin
import kotlinx.coroutines.*

fun main() = runBlocking {
    val job = async {
        throw IllegalStateException("Failure in async")
    }
    job.await()
    println("This line is never reached")
}
ABecause runBlocking does not handle exceptions from child coroutines.
BBecause async does not support exceptions and crashes immediately.
CBecause exceptions in async are thrown only when awaited, and await is not inside try-catch.
DBecause IllegalStateException is not a checked exception and must be caught explicitly.
Attempts:
2 left
💡 Hint
Think about when exceptions from async coroutines are delivered.
📝 Syntax
advanced
2:00remaining
Correct syntax for catch block in coroutine exception handling
Which option contains the correct syntax for the catch block in Kotlin coroutine exception handling?
Kotlin
import kotlinx.coroutines.*

fun main() = runBlocking {
    val handler = CoroutineExceptionHandler { _, exception ->
        println("Caught: ${exception.message}")
    }
    val job = launch(handler) {
        try {
            throw Exception("Oops")
        } catch e: Exception {
            println("Handled inside try-catch")
        }
    }
    job.join()
}
Acatch e: Exception { println("Handled inside try-catch") }
Bcatch (e: Exception) println("Handled inside try-catch")
Ccatch { e: Exception -> println("Handled inside try-catch") }
Dcatch (e: Exception) { println("Handled inside try-catch") }
Attempts:
2 left
💡 Hint
The standard Kotlin syntax for catch is 'catch (e: Exception) { ... }'.
🚀 Application
expert
3:00remaining
How many exceptions are caught and printed?
Given this Kotlin coroutine code, how many exception messages will be printed?
Kotlin
import kotlinx.coroutines.*

fun main() = runBlocking {
    val handler = CoroutineExceptionHandler { _, e ->
        println("Handler caught: ${e.message}")
    }
    val supervisor = SupervisorJob()
    val scope = CoroutineScope(coroutineContext + supervisor + handler)

    val job1 = scope.launch {
        throw RuntimeException("Job1 failed")
    }
    val job2 = scope.launch {
        try {
            throw IllegalArgumentException("Job2 failed")
        } catch (e: IllegalArgumentException) {
            println("Caught in job2: ${e.message}")
        }
    }
    joinAll(job1, job2)
    println("All jobs done")
}
A2
B1
C3
D0
Attempts:
2 left
💡 Hint
Consider which exceptions are caught inside coroutines and which are handled by CoroutineExceptionHandler.

Practice

(1/5)
1. What is the primary way to catch exceptions inside a Kotlin coroutine launched with launch?
easy
A. Use try-catch block inside the coroutine code
B. Use catch method on the coroutine builder
C. Use finally block outside the coroutine
D. Exceptions cannot be caught in coroutines

Solution

  1. Step 1: Understand coroutine exception handling basics

    Exceptions inside launch coroutines are caught by try-catch blocks within the coroutine code itself.
  2. Step 2: Identify correct method to catch exceptions

    The catch method does not exist on coroutine builders, and finally outside coroutine does not catch coroutine exceptions.
  3. Final Answer:

    Use try-catch block inside the coroutine code -> Option A
  4. Quick Check:

    try-catch inside coroutine = correct way [OK]
Hint: Catch exceptions inside coroutine with try-catch [OK]
Common Mistakes:
  • Thinking catch method exists on coroutine builders
  • Using finally block outside coroutine to catch exceptions
  • Assuming exceptions cannot be caught in coroutines
2. Which of the following is the correct syntax to define a CoroutineExceptionHandler in Kotlin?
easy
A. val handler = CoroutineExceptionHandler { println(exception) }
B. val handler = CoroutineExceptionHandler { exception -> println(exception) }
C. val handler = CoroutineExceptionHandler(context, exception -> println(exception))
D. val handler = CoroutineExceptionHandler { context, exception -> println(exception) }

Solution

  1. Step 1: Recall CoroutineExceptionHandler signature

    It takes a lambda with two parameters: context and exception.
  2. 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.
  3. Final Answer:

    val handler = CoroutineExceptionHandler { context, exception -> println(exception) } -> Option D
  4. Quick Check:

    CoroutineExceptionHandler requires (context, exception) lambda [OK]
Hint: CoroutineExceptionHandler lambda needs context and exception [OK]
Common Mistakes:
  • Omitting context parameter in lambda
  • Passing parameters incorrectly
  • Using invalid constructor syntax
3. What will be the output of the following Kotlin code?
import kotlinx.coroutines.*

fun main() = runBlocking {
    val handler = CoroutineExceptionHandler { _, exception ->
        println("Caught: ${exception.message}")
    }
    val job = launch(handler) {
        throw IllegalArgumentException("Invalid argument")
    }
    job.join()
    println("Done")
}
medium
A. Caught: Invalid argument Done
B. Exception in thread "main" java.lang.IllegalArgumentException: Invalid argument
C. Done
D. Caught: null Done

Solution

  1. Step 1: Understand CoroutineExceptionHandler usage

    The handler catches exceptions thrown inside the launch coroutine and prints the message.
  2. Step 2: Trace program output

    The exception message "Invalid argument" is printed by the handler, then "Done" is printed after job.join().
  3. Final Answer:

    Caught: Invalid argument Done -> Option A
  4. 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

  1. 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().
  2. Step 2: Analyze why CoroutineExceptionHandler fails here

    CoroutineExceptionHandler does not catch exceptions from async coroutines because they are deferred until await().
  3. Final Answer:

    CoroutineExceptionHandler does not catch exceptions from async coroutines -> Option C
  4. 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

  1. 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.
  2. 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.
  3. Final Answer:

    Attach a shared CoroutineExceptionHandler to the parent scope and launch coroutines within it -> Option B
  4. 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 unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard