@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