在 Kotlin 中,處理流(Flow)中的異常主要有兩種方法:使用 catch
操作符或使用 onEach
和 launchIn
結合 try-catch
方法 1:使用 catch
操作符
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
fun main() = runBlocking {
simpleFlow()
.catch { e -> println("捕獲到異常: $e") }
.collect { value -> println("收集到的值: $value") }
}
fun simpleFlow(): Flow<Int> = flow {
emit(1)
emit(2)
throw RuntimeException("流處理異常")
emit(3)
}
方法 2:使用 onEach
和 launchIn
結合 try-catch
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
fun main() = runBlocking {
simpleFlow()
.onEach { value ->
try {
// 在這里處理值,可能會拋出異常
println("收集到的值: $value")
} catch (e: Exception) {
println("捕獲到異常: $e")
}
}
.launchIn(this)
}
fun simpleFlow(): Flow<Int> = flow {
emit(1)
emit(2)
throw RuntimeException("流處理異常")
emit(3)
}
在這兩個示例中,我們都創建了一個簡單的流,該流在發射第三個值時會拋出一個異常。在第一個示例中,我們使用 catch
操作符捕獲異常并處理它。在第二個示例中,我們使用 onEach
操作符處理每個值,并在其中使用 try-catch
語句來捕獲和處理異常。