Kotlin Coroutine 初探(三)
和普通方法一样,协程任务执行过程中也会有需要处理异常的情况。
Try Catch
和普通方法一样,使用try catch
进行异常处理。
fun testTryCatch() {
runBlocking {
val job = GlobalScope.launch { // launch 根协程
try {
Log.e("ViewModel", "testTryCatch--Throwing exception from launch")
throw ArithmeticException()
} catch (e: ArithmeticException) {
Log.e("ViewModel", "testTryCatch--Caught ArithmeticException")
}
}
job.join()//等待执行完毕
Log.e("ViewModel", "testTryCatch--Unreached")
}
}
输出:
ExceptionHandler
使用CoroutineExceptionHandler
处理异常。
fun testCoroutineExceptionHandler() {
val handler = CoroutineExceptionHandler { _, exception ->
Log.e("ViewModel", "CoroutineExceptionHandler got $exception")
}
runBlocking {
val job = GlobalScope.launch(handler) { // launch 根协程
Log.e("ViewModel", "testCoroutineExceptionHandler--Throwing exception from launch")
throw ArithmeticException()
}
job.join()//等待执行完毕
Log.e("ViewModel", "testCoroutineExceptionHandler--Unreached")
}
}
输出: