run Catching Cancellable
Like runCatching, but never swallows a CancellationException.
Any other Throwable thrown by block is captured into the returned Result. A CancellationException is rethrown immediately, so cooperative cancellation keeps propagating through the coroutine hierarchy instead of being turned into a failure value.
Example:
val user = runCatchingCancellable { repository.fetchUser(id) }
.getOrElse { fallbackUser }The function is inline, so block may contain non-local returns and suspend calls when invoked from a suspend context. It is the safe replacement for runCatching in suspending code.
Rule: CANCEL_003 (do not catch CancellationException without rethrowing). See docs/BEST_PRACTICES_COROUTINES.md.
Requires opting in to ExperimentalStructuredCoroutines.
Return
Result.success with the value of block, or Result.failure with any non-cancellation Throwable it threw.
Parameters
the computation to run.
See also
Throws
if block throws one (rethrown unchanged).
Receiver variant of runCatchingCancellable: runs block with this as its receiver, capturing ordinary exceptions into a Result and rethrowing CancellationException.
Example:
val size = file.runCatchingCancellable { readBytes().size }Rule: CANCEL_003 (do not catch CancellationException without rethrowing). See docs/BEST_PRACTICES_COROUTINES.md.
Requires opting in to ExperimentalStructuredCoroutines.
Receiver
the object passed to block as this.
Return
Result.success with the value of block, or Result.failure with any non-cancellation Throwable it threw.
Parameters
the computation to run with the receiver as this.
Throws
if block throws one (rethrown unchanged).