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

reactormonk

07/12/2022, 10:00 AM
Shouldn't exceptions thrown in a suspend function bubble up like regular exceptions? Trying to catch a lower one, but it's not properly registered, just aborts the program ... err, works.
b

Big Chungus

07/12/2022, 12:32 PM
That's only true if you're using supervisor scope
r

reactormonk

07/12/2022, 12:34 PM
Wait, what? Exceptions behave differently than with regular functions?
b

Big Chungus

07/12/2022, 12:34 PM
Yes, an exception thrown in sibling job will cancel parent job unless you're in supervisor scope
Concurrent programming is different by nature, so it makes sense that some constructs would behave differently
r

reactormonk

07/12/2022, 12:35 PM
I'm talking about a child function here.
b

Big Chungus

07/12/2022, 12:36 PM
Same thing
Watch some "coroutine exception handling" videos on youtube to get a better grasp
r

reactormonk

07/12/2022, 12:45 PM
So
Copy code
suspend fun a() { suspendCoroutine { block -> block.resumeWithException(IOException()) } }

suspend fun b() { try { a() } catch (e: IOException) { println(e) }
Won't catch the exception?
b

Big Chungus

07/12/2022, 12:50 PM
No unless you use supervisor scope
r

reactormonk

07/12/2022, 12:51 PM
So there's no error channel by default?
... and all exceptions cancel everything by default?
... weird design decision.
I guess I've been coddled too much with Scala Tasks.
b

Big Chungus

07/12/2022, 12:55 PM
Not quite
There are dedicated concurrent ways of handling exceptions
Also there's a good reason behind this decision
I found this explanation by @Lukas Lechner very helpful

https://youtu.be/coq9XDMB-yU?t=479

b

Big Chungus

07/12/2022, 1:01 PM
I found the visuals there quite helpful, but to each its own i guess
r

reactormonk

07/12/2022, 1:09 PM
So if I want an error channel, I can a) add a
coroutineScope { try ... }
or b) start using
suspend fun a(): Result()
and manually pass things along?
n

Nick Allen

07/12/2022, 4:03 PM
@Big Chungus, you seem to be confusing the just calling a suspend method and launching a child coroutine. @reactormonk Exceptions work with suspend methods just like they do for regular methods. Uncaught exceptions bubble up and caught exceptions are stopped. You can see an example here of exceptions working just as you expect. Exceptions become more complicated if you are launching concurrent coroutines. For example:
Copy code
try {
   launch { a() }
} catch (e: IOException) {}
would not catch anything because the exception is in a different coroutine than the one catching so it's not part of the same conceptual call stack.
👍 1
r

reactormonk

07/12/2022, 4:04 PM
kk, makes sense. I was doubting the sanity of the designers.
b

Big Chungus

07/12/2022, 4:13 PM
@Nick Allen guilty as charged. Just rewatched the video I've linked to realize exactly that.
5 Views