Repository: Kotlin/kotlinx.coroutines
File: kotlinx-coroutines-test/common/src/TestBuilders.kt (Kotlin)

Code before:
        scheduler.advanceUntilIdle()
        if (coroutine.isCompleted) {
            /* don't even enter `withTimeout`; this allows to use a timeout of zero to check that there are no
               non-trivial dispatches. */
            completed = true
            continue
        }
        select<Unit> {
            coroutine.onJoin {
                completed = true
            }
            scheduler.onDispatchEvent {
                // we received knowledge that `scheduler` observed a dispatch event, so we reset the timeout
            }
            onTimeout(dispatchTimeoutMs) {
                try {
                    cleanup()
                } catch (e: UncompletedCoroutinesError) {
                    // we expect these and will instead throw a more informative exception just below.
                    emptyList()
                }.throwAll()
                var completing: Boolean
                val completionCause = try {
                    coroutine.tryGetCompletionCause().also { completing = true }
                } catch (e: Throwable) {
                    completing = false
                    null
                }
                var message = "After waiting for $dispatchTimeoutMs ms"
                if (!completing)
                    message += ", the test coroutine is not completing"
                val activeChildren = coroutine.children.filter { it.isActive }.toList()
                if (activeChildren.isNotEmpty())
                    message += ", there were active child jobs: $activeChildren"
                if (completing && activeChildren.isEmpty()) {
                    // some sort of race condition? write something generic.
                    message += ", the test coroutine was not completed"
                }
                val error = UncompletedCoroutinesError(message)
                completionCause?.let { cause -> error.addSuppressed(cause) }
                throw error
            }
        }
    }
    coroutine.getCompletionExceptionOrNull()?.let { exception ->
        val exceptions = try {
            cleanup()
        } catch (e: UncompletedCoroutinesError) {
            // it's normal that some jobs are not completed if the test body has failed, won't clutter the output
            emptyList()
        }

Review comment (suggestion):
instead of `try-catch`, it should be enough to check `coroutine.isCancelled`.
The same goes for `completing`

Code after:
    while (!completed) {
        scheduler.advanceUntilIdle()
        if (coroutine.isCompleted) {
            /* don't even enter `withTimeout`; this allows to use a timeout of zero to check that there are no
               non-trivial dispatches. */
            completed = true
            continue
        }
        select<Unit> {
            coroutine.onJoin {
                completed = true
            }
            scheduler.onDispatchEvent {
                // we received knowledge that `scheduler` observed a dispatch event, so we reset the timeout
            }
            onTimeout(dispatchTimeoutMs) {
                handleTimeout(coroutine, dispatchTimeoutMs, tryGetCompletionCause, cleanup)
            }
        }
    }
    coroutine.getCompletionExceptionOrNull()?.let { exception ->
        val exceptions = try {
            cleanup()
        } catch (e: UncompletedCoroutinesError) {
            // it's normal that some jobs are not completed if the test body has failed, won't clutter the output
            emptyList()
        }
        (listOf(exception) + exceptions).throwAll()
    }
    cleanup().throwAll()
}

/**
 * Invoked on timeout in [runTest]. Almost always just builds a nice [UncompletedCoroutinesError] and throws it.
 * However, sometimes it detects that the coroutine completed, in which case it returns normally.
 */
private inline fun<T: AbstractCoroutine<Unit>> handleTimeout(
    coroutine: T,
    dispatchTimeoutMs: Long,
    tryGetCompletionCause: T.() -> Throwable?,
    cleanup: () -> List<Throwable>,
) {
    val uncaughtExceptions = try {
        cleanup()
    } catch (e: UncompletedCoroutinesError) {
        // we expect these and will instead throw a more informative exception.
        emptyList()
    }
    val activeChildren = coroutine.children.filter { it.isActive }.toList()
    val completionCause = if (coroutine.isCancelled) coroutine.tryGetCompletionCause() else null
    var message = "After waiting for $dispatchTimeoutMs ms"