【发布时间】:2018-10-15 22:13:18
【问题描述】:
在这段代码中为什么handler 只打印JobCancellationException 而不是SocketException 的堆栈跟踪? launch 内部的 foo 函数肯定会抛出 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)
}
【问题讨论】:
-
我认为 runBlocking 不会处理 CoroutineExceptionHandler