在这段代码中,为什么handler
只打印堆栈跟踪JobCancellationException
而不是SocketException
?里面的foo
函数launch
肯定是 throws SocketException
,那么它会发生什么?
suspend fun foo() {
val job = coroutineContext[Job]!!
val socket = Socket()
job.invokeOnCompletion(onCancelling = true) {
if (!socket.isClosed) {
socket.close()
}
}
// non-routable address -> timeout
// will throw SocketException after socket.close() is called above
socket.connect(InetSocketAddress("10.0.0.0", 1234), 2000)
}
fun test() = runBlocking {
val handler = CoroutineExceptionHandler { _, throwable ->
throwable.printStackTrace()
}
val job = launch(DefaultDispatcher + handler) {
foo()
}
delay(100)
job.cancelAndJoin()
delay(100)
}