`async {}` throws exception not until `.await()` b...
# coroutines
l
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
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
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
My suggestion that doesn't require a
supervisorScope
works for both
async
and
launch
FYI.
✔️ 1