【问题标题】:GlobalScope coroutine not logging error to consoleGlobalScope 协程未将错误记录到控制台
【发布时间】:2019-08-28 03:26:48
【问题描述】:

为什么下面的代码没有将 TimeoutCancellationException 记录到控制台?

@Test fun noExceptionLogged(){
    GlobalScope.launch{
        withTimeout(4000) {
            repeat(1000) { i ->
                println("I'm sleeping $i ...")
                delay(500L)
            }
        }
    }
    Thread.sleep(20_000)
}

【问题讨论】:

    标签: kotlin kotlin-coroutines


    【解决方案1】:

    由于GlobalScope 的性质,它似乎是这样工作的。它不能被取消,所以它吞噬了CancellationException。

    GlobalScope.launch { // won't print anything
        throw CancellationException()
    }
    
    GlobalScope.launch { // will print stacktrace
        throw RuntimeException()
    }
    
    runBlocking { // will print stackrace
        throw RuntimeException()
    }
    
    GlobalScope.launch { // will print "Hello!"
        try {
            throw CancellationException()
        } catch (e: Exception) {
            println("Hello!")
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-15
      • 2017-08-06
      • 2018-03-10
      • 2018-11-23
      • 1970-01-01
      • 2012-07-07
      • 2015-04-25
      相关资源
      最近更新 更多