协程,异常处理和withTimeout。不能把我的头缠在这个组合上

时间:2020-04-15 15:16:04

标签: kotlin kotlin-coroutines

import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
import kotlin.system.measureTimeMillis

fun time() = System.currentTimeMillis()

fun main(args: Array<String>) {
    runBlocking {
        repeat(5) {
            try {
                println("${time()} withTimeout before")
                withTimeout(1L) {
                    try {
                        delay(200L)
                    } catch (e: Exception) {
                        println("${time()} withTimeout exception " + e.localizedMessage)
                    }
                }
                println("${time()} withTimeout done")
            } catch (e: Exception) {
                println("${time()} exception " + e.localizedMessage)
            }
            println("${time()} -----")
        }
    }
}

这给了我输出:

1586923684774 withTimeout before
1586923684788 withTimeout exception Timed out waiting for 1 ms
1586923684789 withTimeout done
1586923684789 -----
1586923684789 withTimeout before
1586923684790 withTimeout exception Timed out waiting for 1 ms
1586923684791 exception Timed out waiting for 1 ms
1586923684791 -----
1586923684791 withTimeout before
1586923684792 withTimeout exception Timed out waiting for 1 ms
1586923684792 exception Timed out waiting for 1 ms
1586923684792 -----
1586923684792 withTimeout before
1586923684794 withTimeout exception Timed out waiting for 1 ms
1586923684794 exception Timed out waiting for 1 ms
1586923684794 -----
1586923684794 withTimeout before
1586923684795 withTimeout exception Timed out waiting for 1 ms
1586923684795 exception Timed out waiting for 1 ms
1586923684795 -----

在第一个循环中,withTimeout done被打印。

问题1:为什么只在第一次迭代?

问题2:如果我将 withTimeout 中的等待时间从1L更改为10L,则不会打印出来。相反,异常会传播到外部try / catch,就像在下一次迭代中一样(请参见下文)。为什么?

1586923727317 withTimeout before
1586923727333 withTimeout exception Timed out waiting for 10 ms
1586923727334 exception Timed out waiting for 10 ms
1586923727334 -----
1586923727334 withTimeout before
1586923727347 withTimeout exception Timed out waiting for 10 ms
1586923727347 exception Timed out waiting for 10 ms
1586923727347 -----
1586923727347 withTimeout before
1586923727360 withTimeout exception Timed out waiting for 10 ms
1586923727360 exception Timed out waiting for 10 ms
1586923727360 -----
1586923727360 withTimeout before
1586923727370 withTimeout exception Timed out waiting for 10 ms
1586923727371 exception Timed out waiting for 10 ms
1586923727371 -----
1586923727371 withTimeout before
1586923727382 withTimeout exception Timed out waiting for 10 ms
1586923727382 exception Timed out waiting for 10 ms
1586923727382 -----

问题3:为什么即使将该异常捕获在 withTimeout() 中的try / catch块中,却将其传播到外部try / catch块中?

在此先感谢并感谢您的帮助。

0 个答案:

没有答案