前置知识: Kotlin

协程异常处理

1 minAdvanced2026/6/14

Kotlin协程异常处理:CoroutineExceptionHandler、SupervisorJob。

1. 异常传播

val scope = CoroutineScope(Dispatchers.Default)

// 默认:子协程失败会取消父协程和兄弟协程
scope.launch {
    launch { throw Exception("child 1 fails") }
    launch { delay(1000); println("child 2") }  // 被取消
}

2. SupervisorJob

// 子协程失败不影响其他子协程
val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)

scope.launch {
    launch { throw Exception("child 1 fails") }
    launch { delay(1000); println("child 2") }  // 正常执行
}

3. CoroutineExceptionHandler

val handler = CoroutineExceptionHandler { _, exception ->
    println("Caught: $exception")
}

scope.launch(handler) {
    throw Exception("error")
}

4. supervisorScope

supervisorScope {
    launch { throw Exception("A fails") }
    launch { delay(100); println("B runs") }
}
// A 失败不影响 B

5. try-catch 限制

//  捕获不到 launch 的异常
try {
    launch { throw Exception() }
} catch (e: Exception) { }

//  使用 async + await
try {
    val deferred = async { throw Exception() }
    deferred.await()
} catch (e: Exception) { }