MST

星途 面试题库

面试题:Kotlin协程的异常处理机制及应用场景

阐述Kotlin协程中处理异常的几种方式,如`try - catch`块、`CoroutineExceptionHandler`等,并举例说明在网络请求、文件读取等异步场景下如何合理运用这些异常处理机制来确保程序的稳定性和健壮性。
18.7万 热度难度
编程语言Kotlin

知识考点

AI 面试

面试题答案

一键面试

使用try - catch块

在Kotlin协程中,try - catch块可用于捕获协程内抛出的异常。例如在网络请求场景:

import kotlinx.coroutines.*

fun main() = runBlocking {
    try {
        val result = withContext(Dispatchers.IO) {
            // 模拟网络请求
            delay(2000)
            if (Math.random() < 0.5) {
                throw IOException("网络请求失败")
            }
            "网络请求成功"
        }
        println(result)
    } catch (e: IOException) {
        println("捕获到网络请求异常: ${e.message}")
    }
}

在文件读取场景:

import kotlinx.coroutines.*
import java.io.File

fun main() = runBlocking {
    try {
        val result = withContext(Dispatchers.IO) {
            val file = File("nonexistent.txt")
            file.readText()
        }
        println(result)
    } catch (e: FileNotFoundException) {
        println("捕获到文件读取异常: ${e.message}")
    }
}

使用CoroutineExceptionHandler

CoroutineExceptionHandler 用于全局处理未捕获的异常。先定义一个 CoroutineExceptionHandler

val handler = CoroutineExceptionHandler { _, exception ->
    println("全局捕获到异常: ${exception.message}")
}

在网络请求场景使用:

import kotlinx.coroutines.*

fun main() = runBlocking {
    GlobalScope.launch(handler + Dispatchers.IO) {
        delay(2000)
        if (Math.random() < 0.5) {
            throw IOException("网络请求失败")
        }
        println("网络请求成功")
    }
    delay(3000)
}

在文件读取场景使用:

import kotlinx.coroutines.*
import java.io.File

fun main() = runBlocking {
    GlobalScope.launch(handler + Dispatchers.IO) {
        val file = File("nonexistent.txt")
        file.readText()
    }
    delay(3000)
}

在异步场景中合理运用

  • try - catch:适用于对特定代码块内的异常进行捕获和处理,逻辑清晰,适用于对单个操作进行细粒度的异常处理。如网络请求和文件读取中,我们明确知道可能抛出的异常类型,对其进行针对性捕获处理。
  • CoroutineExceptionHandler:适合处理全局的未捕获异常,比如在多个协程中都可能出现的类似异常,通过全局的 CoroutineExceptionHandler 统一处理,避免每个协程都写重复的 try - catch 块,提高代码的简洁性和可维护性。但要注意,它处理的是未被 try - catch 块捕获的异常。