Shouldn't exceptions thrown in a suspend function ...
# coroutines
r
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
That's only true if you're using supervisor scope
r
Wait, what? Exceptions behave differently than with regular functions?
b
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
I'm talking about a child function here.
b
Same thing
Watch some "coroutine exception handling" videos on youtube to get a better grasp
r
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
No unless you use supervisor scope
r
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
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
I found the visuals there quite helpful, but to each its own i guess
r
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
@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
kk, makes sense. I was doubting the sanity of the designers.
b
@Nick Allen guilty as charged. Just rewatched the video I've linked to realize exactly that.