谢朋刚
08/01/2025, 3:01 AMresumeWithException
and directly throwing an Exception
within a suspend function?Youssef Shoaib [MOD]
08/01/2025, 3:16 AMresume
with something that immediately results in an exception? It's identical!谢朋刚
08/01/2025, 3:21 AMsuspend
funciton using suspendCoroutine, you can use resumeWithException
to throw an Exception
@SinceKotlin("1.3")
@InlineOnly
public inline fun <T> Continuation<T>.resumeWithException(exception: Throwable): Unit =
resumeWith(Result.failure(exception))
谢朋刚
08/01/2025, 3:22 AMException
directly.谢朋刚
08/01/2025, 3:22 AMYoussef Shoaib [MOD]
08/01/2025, 3:32 AMresumeWithException
.
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谢朋刚
08/01/2025, 3:45 AMZach Klippenstein (he/him) [MOD]
08/01/2025, 4:16 AM谢朋刚
08/01/2025, 5:13 AMDmitry Khalanskiy [JB]
08/01/2025, 9:48 AMsuspend
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
!