【问题标题】:Handle exception both in coroutine handler and try-catch block在协程处理程序和 try-catch 块中处理异常
【发布时间】:2019-12-24 16:23:20
【问题描述】:
如果我们有类似的基本处理程序
protected val baseHandler = CoroutineExceptionHandler { _, e ->
handleError(e)
}
并通过 try-catch 块执行我们的代码
scope.launch(baseHandler){
try{
throw ...
}
catch(e:Exception) {
}
是否可以先在 catch 块中处理异常,然后在基本处理程序中作为后备处理?
这段代码的目标是为所有项目协程提供一个基本的异常处理程序。
【问题讨论】:
标签:
kotlin
kotlin-coroutines
【解决方案1】:
您创建并传入的CoroutineExceptionHandler 将用于协程中未处理的异常。
例如,如果您想捕获Exception 的一种特定类型,并处理CoroutineExceptionHandler 中的所有其他异常,您可以针对该类型使用try-catch:
GlobalScope.launch(baseHandler) {
try {
throw IllegalStateException("oh no it failed")
} catch (e: IllegalStateException) {
// Handles the exception
}
}
如果在 try 块内引发除 IllegalStateException 之外的异常,则会传播到您的处理程序。
或者,您可以在 catch 分支中捕获东西,但如果您无法在那里处理它,则重新抛出它们,并希望将其留给处理程序:
GlobalScope.launch(baseHandler) {
try {
// Code that can throw exceptions
} catch (e: Exception) {
if (/* some condition */) {
throw e
}
}
}