0
0
Android Kotlinmobile~10 mins

Exception handling in coroutines in Android Kotlin - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to catch exceptions inside a coroutine using try-catch.

Android Kotlin
launch {
  try {
    // some suspend function call
  } catch (e: [1]) {
    println("Error caught")
  }
}
Drag options to blanks, or click blank then click option'
AException
BError
CCancellationException
DThrowable
Attempts:
3 left
💡 Hint
Common Mistakes
Using Error instead of Exception
Catching CancellationException which is usually rethrown
2fill in blank
medium

Complete the code to handle exceptions globally in a CoroutineScope using a handler.

Android Kotlin
val handler = CoroutineExceptionHandler { _, [1] ->
  println("Caught: $[1]")
}

CoroutineScope(Dispatchers.Main + handler).launch {
  // coroutine code
}
Drag options to blanks, or click blank then click option'
Aerror
Bthrowable
Cexception
De
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'throwable' instead of 'exception'
Using 'error' which is not the parameter name
3fill in blank
hard

Fix the error in the code to properly handle cancellation exceptions separately.

Android Kotlin
try {
  withContext(Dispatchers.IO) {
    // some suspend call
  }
} catch (e: [1]) {
  println("Cancelled")
} catch (e: Exception) {
  println("Other error")
}
Drag options to blanks, or click blank then click option'
AError
BCancellationException
CThrowable
DException
Attempts:
3 left
💡 Hint
Common Mistakes
Catching Exception first and missing cancellation
Catching Throwable which is too broad
4fill in blank
hard

Fill both blanks to create a supervisor scope that handles child coroutine failures independently.

Android Kotlin
supervisorScope {
  val job = launch [1] {
    throw RuntimeException("Fail")
  }
  job [2] {
    println("Child failed")
  }
}
Drag options to blanks, or click blank then click option'
ASupervisorJob()
Bjoin()
CinvokeOnCompletion
Dcancel()
Attempts:
3 left
💡 Hint
Common Mistakes
Using cancel instead of invokeOnCompletion
Using join which waits but does not handle completion callbacks
5fill in blank
hard

Fill all three blanks to create a coroutine with a handler that logs exceptions and rethrows cancellation.

Android Kotlin
val handler = CoroutineExceptionHandler { _, e ->
  if (e is [1]) throw e
  else println("Error: $e")
}

CoroutineScope(Dispatchers.Default + handler).launch {
  try {
    // some suspend call
  } catch (e: [2]) {
    println("Caught: $e")
  }
}

fun main() {
  val job = CoroutineScope(Dispatchers.Default + handler).launch {
    throw [3]("Oops")
  }
}
Drag options to blanks, or click blank then click option'
ACancellationException
BException
CRuntimeException
DError
Attempts:
3 left
💡 Hint
Common Mistakes
Catching CancellationException in try-catch instead of rethrowing
Throwing Error which is not recommended