0Pricing
Kotlin Academy · 课时

CoroutineExceptionHandler:全局未捕获异常处理器

安装 CoroutineExceptionHandler,以记录未处理的异常或从中恢复。

CoroutineExceptionHandler:全局未捕获异常处理器 是 CoddyKit 上的免费 Kotlin Academy 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Kotlin Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Kotlin Academy 课程共包含 4 节课。

什么是 CoroutineExceptionHandler?

CoroutineExceptionHandler 是一种上下文元素,用于处理没有捕获处理器的协程所抛出的未捕获异常。它充当最后一道防线。

import kotlinx.coroutines.*
val handler = CoroutineExceptionHandler { context, exception ->
    println("Caught unhandled: ${exception.message}")
}
fun main() = runBlocking {
    val scope = CoroutineScope(Dispatchers.Default + handler)
    scope.launch { throw RuntimeException("oops") }
    delay(100)
}

仅适用于根协程

CoroutineExceptionHandler 只捕获根协程的异常(直接在作用域上启动的协程)。子协程会将异常传播给父协程,而不是交给处理器。

import kotlinx.coroutines.*
val handler = CoroutineExceptionHandler { _, e -> println("Handler: ${e.message}") }
fun main() = runBlocking {
    // Root coroutine — handler fires:
    CoroutineScope(handler).launch {
        throw RuntimeException("root error")
    }
    delay(100)
    // NOT handler (child of coroutineScope):
    // launch { launch { throw RuntimeException() } }
}

不会抑制异常

处理器会在异常已经取消协程之后才被调用。它用于记录日志、报告崩溃或执行清理,而不是恢复执行。

import kotlinx.coroutines.*
val handler = CoroutineExceptionHandler { _, e ->
    println("[CrashReport] ${e::class.simpleName}: ${e.message}")
    // send to Crashlytics, Sentry, etc.
}
fun main() = runBlocking {
    CoroutineScope(SupervisorJob() + handler).apply {
        launch { throw IllegalStateException("state error") }
        launch { delay(100); println("still alive") }
        delay(200)
        cancel()
    }
}

处理器 + SupervisorJob

SupervisorJob + CoroutineExceptionHandler 的组合是长生命周期作用域的标准模式:子协程彼此独立地失败,同时记录未处理的失败。

import kotlinx.coroutines.*
class AppScope {
    private val handler = CoroutineExceptionHandler { _, e ->
        println("Uncaught: ${e.message}")
    }
    val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default + handler)
}
fun main() = runBlocking {
    val app = AppScope()
    app.scope.launch { throw RuntimeException("task failed") }
    app.scope.launch { delay(100); println("other task ok") }
    delay(200)
    app.scope.cancel()
}

处理器与异步操作

对于 async,异常会存储在 Deferred 中,并在调用 await() 时抛出。除非 deferred 未被等待,否则处理器不会触发(NOT)。

import kotlinx.coroutines.*
val handler = CoroutineExceptionHandler { _, e -> println("Handler: ${e.message}") }
fun main() = runBlocking {
    val scope = CoroutineScope(SupervisorJob() + handler)
    val deferred = scope.async { throw RuntimeException("async error") }
    try {
        deferred.await()  // exception thrown here
    } catch (e: RuntimeException) {
        println("Caught from await: ${e.message}")
    }
    delay(50)
    scope.cancel()
}

与 Thread.UncaughtExceptionHandler 的比较

与 Java 的 UncaughtExceptionHandler 不同,Kotlin 的处理器属于协程上下文,并且只适用于该作用域内的协程。

import kotlinx.coroutines.*
// Java style (applies to threads):
Thread.setDefaultUncaughtExceptionHandler { t, e ->
    println("Thread ${t.name} threw: ${e.message}")
}
// Kotlin coroutine style (applies to coroutines in scope):
val handler = CoroutineExceptionHandler { _, e ->
    println("Coroutine threw: ${e.message}")
}
fun main() = runBlocking { println("Handlers target different concurrency models") }

使用 MDC 的日志记录模式

在服务器应用中,处理器可以在将异常转交给日志框架之前,捕获协程上下文信息(例如请求 ID),以便进行结构化日志记录。

import kotlinx.coroutines.*
val handler = CoroutineExceptionHandler { ctx, e ->
    val jobName = ctx[CoroutineName]?.name ?: "unknown"
    println("[${jobName}] ERROR: ${e.message}")
}
fun main() = runBlocking {
    CoroutineScope(SupervisorJob() + handler).launch(CoroutineName("DataLoader")) {
        throw RuntimeException("fetch failed")
    }
    delay(100)
}

集成崩溃报告

使用处理器将未捕获的异常转交给 Firebase Crashlytics 或 Sentry 等崩溃报告服务。

import kotlinx.coroutines.*
object CrashReporter {
    fun record(e: Throwable) = println("[Crashlytics] ${e.message}")
}
val handler = CoroutineExceptionHandler { _, e ->
    if (e !is CancellationException) CrashReporter.record(e)
}
val appScope = CoroutineScope(SupervisorJob() + Dispatchers.Default + handler)
fun main() = runBlocking {
    appScope.launch { throw RuntimeException("unhandled in production") }
    delay(100)
    appScope.cancel()
}

处理器继承

父上下文中的处理器不会被子协程自动继承。处理器必须位于根协程的上下文中,才能被触发。

import kotlinx.coroutines.*
val handler = CoroutineExceptionHandler { _, e -> println("Handler: ${e.message}") }
fun main() = runBlocking {
    // Handler only fires at root level:
    CoroutineScope(SupervisorJob() + handler).launch {
        // Child of root — exception propagates to root handler:
        launch { throw RuntimeException("nested") }
    }
    delay(100)
}

最佳实践总结

始终在应用级或功能级作用域上安装 CoroutineExceptionHandler。记录每个非取消异常。不要依赖它来控制流程——它只用于可观测性。

import kotlinx.coroutines.*
val globalHandler = CoroutineExceptionHandler { ctx, e ->
    if (e !is CancellationException) {
        println("[ERROR] ${ctx[CoroutineName]?.name}: ${e.message}")
    }
}
val appScope = CoroutineScope(SupervisorJob() + Dispatchers.Default + globalHandler)
fun main() = runBlocking {
    appScope.launch(CoroutineName("Auth")) { throw RuntimeException("token expired") }
    delay(100); appScope.cancel()
}

快速检查

对于哪种协程类型,CoroutineExceptionHandler 不会自动触发?

回顾

CoroutineExceptionHandler 是根协程中未捕获异常的最后一道观察机制。将它与 SupervisorJob 结合,用于长生命周期作用域。请使用它记录日志和报告崩溃,而不要用于控制流程。

常见问题解答

「CoroutineExceptionHandler:全局未捕获异常处理器」课时是免费的吗?

是的 — 「CoroutineExceptionHandler:全局未捕获异常处理器」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Kotlin Academy 课程的其余内容,请升级到 CoddyKit PRO。 Kotlin Academy 课程共包含 4 节课。

「CoroutineExceptionHandler:全局未捕获异常处理器」这节课中我会学到什么?

安装 CoroutineExceptionHandler,以记录未处理的异常或从中恢复。 你通过在浏览器中直接运行的动手代码来练习 Kotlin Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Kotlin Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Kotlin Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「CoroutineExceptionHandler:全局未捕获异常处理器」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Kotlin Academy 课中编写并运行代码吗?

能。每节 Kotlin Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. SupervisorJob 与 Job:故障隔离
  2. CoroutineExceptionHandler:全局未捕获异常处理器
  3. async/await 异常传播
  4. 设计弹性的协程架构
← 返回 Kotlin Academy