Does anyone know the difference between using `res...
# coroutines
u
Does anyone know the difference between using
resumeWithException
and directly throwing an
Exception
within a suspend function?
y
You mean like if you
resume
with something that immediately results in an exception? It's identical!
u
If writes a
suspend
funciton using suspendCoroutine, you can use
resumeWithException
to throw an
Exception
Copy code
@SinceKotlin("1.3")
@InlineOnly
public inline fun <T> Continuation<T>.resumeWithException(exception: Throwable): Unit =
    resumeWith(Result.failure(exception))
but we also can throwing an
Exception
directly.
What is the difference?
y
Both are identical in this case. `suspendCoroutine`'s block, if it raises an error, will be propagated as if you called
resumeWithException
. However, you won't go through the dispatcher for instance, so actually throwing directly is ever so slightly more performant, while
resumeWithException
might allocate some objects
u
Under what circumstances would these two behaviors differ?
z
The behavior should be the same in every case, I think. Why do you ask? Are you seeing something unexpected?
u
I'm just wondering, what was the intention behind Kotlin's design of this function?
d
The intention is to allow other parts of the system to make this function throw an exception, after the
suspend
function has already suspended. You are right that there really isn't much sense in suspending if you already know you already know you're going to throw an exception. Please see the code snippet in the documentation https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/suspend-cancellable-coroutine.html for a typical usage example of
resumeWithException
!