Kotlin 协程 异常与取消

    @Test
    fun `test cancel and exception`() = runBlocking<Unit> {
        val job1 = launch {
            val child = launch {
                try {
                    delay(Long.MAX_VALUE)
                } finally {
                    println("Child is cancelled.")
                }
            }
            yield()
            println("取消子协程")
            child.cancelAndJoin()
            yield()
            println("父协程没有被取消")

        }

        job1.join()

    }

取消的时候如果伴随其他的异常。。那么执行顺序是这样的


    @Test
    fun `test cancel and exception2`() = runBlocking<Unit> {
        val coroutineExceptionHandler = CoroutineExceptionHandler { _, exception ->
            println("Caught $exception")
        }
        val job = GlobalScope.launch(coroutineExceptionHandler) {
            launch {
                try {
                    delay(Long.MAX_VALUE)
                } finally {
                    withContext(NonCancellable) {
                        println("children are cancel ,but exception is not handled until all children terminate")
                        delay(100)
                        println("The first child finished it's non cancellable block")
                    }
                }
            }

            launch {
                delay(10)
                println("Second child throws an exception")
                throw ArithmeticException()
            }

        }
        job.join()
    }

 

 也不难理解

取消的本身就伴随一个异常的 就是

JobCancellationException

猜你喜欢

转载自blog.csdn.net/mp624183768/article/details/126458318