Bird
Raised Fist0
Kotlinprogramming~20 mins

CoroutineExceptionHandler in Kotlin - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
CoroutineExceptionHandler Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this CoroutineExceptionHandler example?
Consider the following Kotlin code using CoroutineExceptionHandler. What will be printed when this code runs?
Kotlin
import kotlinx.coroutines.*

fun main() = runBlocking {
    val handler = CoroutineExceptionHandler { _, exception ->
        println("Caught: ${exception.message}")
    }

    val job = GlobalScope.launch(handler) {
        throw AssertionError("My custom error")
    }
    job.join()
    println("Done")
}
ANo output
BException is not caught, program crashes
C
Caught: My custom error
Done
D
Done
Caught: My custom error
Attempts:
2 left
💡 Hint
CoroutineExceptionHandler catches uncaught exceptions in coroutines launched with it.
❓ Predict Output
intermediate
2:00remaining
What happens if CoroutineExceptionHandler is used with async builder?
Look at this Kotlin code snippet. What will be the output or behavior?
Kotlin
import kotlinx.coroutines.*

fun main() = runBlocking {
    val handler = CoroutineExceptionHandler { _, exception ->
        println("Caught: ${exception.message}")
    }

    val deferred = async(handler) {
        throw IllegalStateException("Error in async")
    }

    try {
        deferred.await()
    } catch (e: Exception) {
        println("Caught in try: ${e.message}")
    }
}
A
Caught: Error in async
Caught in try: Error in async
BCaught in try: Error in async
CCaught: Error in async
DNo output, program hangs
Attempts:
2 left
💡 Hint
CoroutineExceptionHandler does not catch exceptions from async builder.
🔧 Debug
advanced
2:00remaining
Why does this CoroutineExceptionHandler not catch the exception?
This Kotlin code uses CoroutineExceptionHandler but the exception is not caught by it. Why? fun main() = runBlocking { val handler = CoroutineExceptionHandler { _, exception -> println("Caught: ${exception.message}") } val job = launch { throw RuntimeException("Oops") } job.join() println("Finished") }
ABecause the handler was not passed to launch, so it can't catch exceptions
BBecause runBlocking swallows exceptions silently
CBecause RuntimeException is not caught by CoroutineExceptionHandler
DBecause job.join() suppresses exceptions
Attempts:
2 left
💡 Hint
CoroutineExceptionHandler must be passed to the coroutine builder to work.
📝 Syntax
advanced
2:00remaining
Which option correctly creates a CoroutineExceptionHandler?
Select the correct Kotlin syntax to create a CoroutineExceptionHandler that prints the exception message.
Aval handler = CoroutineExceptionHandler { exception -> println("Error: ${exception.message}") }
Bval handler = CoroutineExceptionHandler { (context, exception) -> println("Error: ${exception.message}") }
Cval handler = CoroutineExceptionHandler(context, exception) -> println("Error: ${exception.message}")
Dval handler = CoroutineExceptionHandler { context, exception -> println("Error: ${exception.message}") }
Attempts:
2 left
💡 Hint
CoroutineExceptionHandler takes a lambda with two parameters: CoroutineContext and Throwable.
🚀 Application
expert
3:00remaining
How many exceptions will be caught by this CoroutineExceptionHandler?
Given this Kotlin code, how many exceptions will the CoroutineExceptionHandler catch and print?
Kotlin
import kotlinx.coroutines.*

fun main() = runBlocking {
    val handler = CoroutineExceptionHandler { _, exception ->
        println("Caught: ${exception.message}")
    }

    val supervisor = SupervisorJob()
    val scope = CoroutineScope(coroutineContext + supervisor + handler)

    scope.launch {
        throw IllegalArgumentException("First error")
    }

    scope.launch {
        try {
            throw IllegalStateException("Second error")
        } catch (e: Exception) {
            println("Caught locally: ${e.message}")
        }
    }

    scope.async {
        throw ArithmeticException("Third error")
    }

    delay(100)
}
A1
B3
C2
D0
Attempts:
2 left
💡 Hint
CoroutineExceptionHandler catches uncaught exceptions in launch coroutines but not in async or caught exceptions.

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

  1. Step 1: Understand CoroutineExceptionHandler role

    It is designed to catch exceptions that are not handled inside coroutines.
  2. Step 2: Compare with other coroutine features

    Launching coroutines, cancelling, or delaying are different coroutine features, not related to exception handling.
  3. Final Answer:

    To catch uncaught exceptions in coroutines and handle them -> Option D
  4. Quick Check:

    CoroutineExceptionHandler catches exceptions = A [OK]
Hint: Remember: ExceptionHandler catches errors outside try-catch [OK]
Common Mistakes:
  • Confusing CoroutineExceptionHandler with coroutine launch or delay
  • Thinking it cancels coroutines instead of handling exceptions
  • Assuming it handles exceptions inside try-catch blocks
2. Which of the following is the correct way to create a CoroutineExceptionHandler in Kotlin?
easy
A. val handler = CoroutineExceptionHandler { context, exception -> println(exception) }
B. val handler = CoroutineExceptionHandler(context, exception -> println(exception))
C. val handler = CoroutineExceptionHandler(context) { exception -> println(exception) }
D. val handler = CoroutineExceptionHandler { exception -> println(exception) }

Solution

  1. Step 1: Recall CoroutineExceptionHandler syntax

    It takes a lambda with two parameters: CoroutineContext and Throwable.
  2. Step 2: Check options for correct lambda signature

    val handler = CoroutineExceptionHandler { context, exception -> println(exception) } matches the correct syntax: { context, exception -> ... }.
  3. Final Answer:

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

    Correct lambda parameters = A [OK]
Hint: Remember: Handler lambda needs (context, exception) parameters [OK]
Common Mistakes:
  • Using only one parameter in lambda
  • Passing parameters incorrectly with parentheses
  • Confusing syntax with other coroutine builders
3. What will be the output of the following Kotlin code?
val handler = CoroutineExceptionHandler { _, exception -> println("Caught: ${exception.message}") }

GlobalScope.launch(handler) {
    throw IllegalArgumentException("Invalid argument")
}
Thread.sleep(100)
medium
A. Caught: java.lang.IllegalArgumentException
B. Caught: Invalid argument
C. No output, exception ignored
D. Exception not caught, program crashes

Solution

  1. Step 1: Understand CoroutineExceptionHandler usage

    The handler catches uncaught exceptions and prints the message.
  2. Step 2: Analyze the thrown exception message

    The exception is IllegalArgumentException with message "Invalid argument".
  3. Final Answer:

    Caught: Invalid argument -> Option B
  4. Quick Check:

    Exception message printed = D [OK]
Hint: Exception message prints inside handler lambda [OK]
Common Mistakes:
  • Expecting program crash instead of caught exception
  • Confusing exception object with its message
  • Ignoring Thread.sleep needed for coroutine to run
4. Identify the error in this Kotlin coroutine code using CoroutineExceptionHandler:
val handler = CoroutineExceptionHandler { context, exception ->
    println("Error: ${exception.message}")
}

GlobalScope.launch {
    throw RuntimeException("Failure")
}
medium
A. Exception type is wrong
B. Lambda parameters are incorrect
C. CoroutineExceptionHandler is not added to coroutine context
D. GlobalScope.launch cannot throw exceptions

Solution

  1. Step 1: Check how handler is used

    The handler is defined but not passed to launch coroutine context.
  2. Step 2: Understand consequence

    Without adding handler to launch, exceptions are uncaught and not handled by it.
  3. Final Answer:

    CoroutineExceptionHandler is not added to coroutine context -> Option C
  4. 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

Solution

  1. Step 1: Understand CoroutineScope context inheritance

    Coroutines inherit context from their CoroutineScope, including exception handlers.
  2. Step 2: Apply handler to CoroutineScope context

    Adding CoroutineExceptionHandler to the scope ensures all launched coroutines use it automatically.
  3. Final Answer:

    Add the CoroutineExceptionHandler to the CoroutineScope's context when creating it -> Option A
  4. Quick Check:

    Handler in scope context applies to all coroutines = B [OK]
Hint: Attach handler to scope context for all coroutines [OK]
Common Mistakes:
  • Adding handler only to some coroutines
  • Relying on try-catch inside coroutines instead
  • Using global try-catch which doesn't catch coroutine exceptions
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