小编Ser*_*any的帖子

为什么挂起函数在finally中会抛出异常

正如标题所说,为什么挂起函数会抛出异常finally

对于常规函数,finally-block 会执行所有函数:

import kotlinx.coroutines.*

fun main() {
    val handler = CoroutineExceptionHandler { _, exception ->
        println("Caught $exception")
    }
    val job = GlobalScope.launch(handler) {
        launch {
            // the first child
            try {
                println("inside try")
                delay(1000)
            } finally {

                println("Children are cancelled, but exception is not handled until all children terminate")

                Thread.sleep(1000)
                println("thread.sleep executed")
                //foo()
                println("The first child finished its non cancellable block")

            }
        }
        launch {
            // the second child
            delay(10)
            println("Second child throws an exception") …
Run Code Online (Sandbox Code Playgroud)

kotlin kotlinx.coroutines kotlin-coroutines

2
推荐指数
1
解决办法
1506
查看次数