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

lesincs

07/02/2022, 5:02 AM
async {}
throws exception not until
.await()
be called.
Copy code
val scope = MainScope()
scope.launch {
    val deferred = async<String> {
        delay(200)
        throw RuntimeException()
    }

    try {
        val result = deferred.await()
        print(result)
    } catch (e: Exception) {
        print("catch exception")
    }
}
In this code snippet, the
try catch
is not gonna work, which confused me that isn’t
async
throwing exceptions only when
await()
is called, so the exception should be catched?
l

louiscad

07/04/2022, 3:18 AM
You need to wrap the code calling
async
with a local
coroutineScope { … }
, and surround that block with the try catch you want. Otherwise, you're breaking structured concurrency, which leads to the surprising behavior you've been witnessing.
Here (video timestamp in the link), I explain structured concurrency, with examples where the
async
function is used:

https://youtu.be/P1eeS6DQ5Uo?t=1367

👍 1
I also cover it earlier in the talk if you're curious, but with
launch
in place of
async
(it works exactly the same way):

https://youtu.be/P1eeS6DQ5Uo?t=803

l

lesincs

07/04/2022, 11:30 AM
Thanks Louis, I finally wrapped my whole code inside a
supervisorScope
, and then it works as I am expecting, and I think if I use
launch
instead of
async
, I would like to take your suggestion, use
coroutineScope
and then try catch it, thanks again.😁
l

louiscad

07/04/2022, 11:45 AM
My suggestion that doesn't require a
supervisorScope
works for both
async
and
launch
FYI.
✔️ 1
3 Views