https://kotlinlang.org logo
#coroutines
Title
# coroutines
p

Paul Woitaschek

06/05/2019, 11:33 AM
Copy code
import kotlinx.coroutines.*

val job: Job = Job()
val scope = CoroutineScope(Dispatchers.Default + job)

fun throwsAsync(): Deferred<Unit> = scope.async {
  throw Exception()
}

fun loadData() = scope.launch {
  throwsAsync().await()
}

suspend fun main() {
  loadData().join()
  scope.launch { println("worked") }.join()
  joinAll()
  println("done")
}
Why doesn't this crash?
m

marstran

06/05/2019, 11:45 AM
I think it's because
launch
is a fire&forget type of coroutine builder. The caller is not expected to handle errors. You need to register a
CoroutineExceptionHandler
on it: https://kotlinlang.org/docs/reference/coroutines/exception-handling.html#coroutineexceptionhandler
async().await()
however, will throw when you do
await()
.
4 Views