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.
louiscad
07/04/2022, 3:21 AM
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
louiscad
07/04/2022, 3:23 AM
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