使用kotlinx.coroutines lib如果在取消协程后抛出异常,我就无法捕获异常.这会导致应用崩溃.
fun foo() { val job = launch(UI) { try { Log.d("TAG", "Start coroutine") run(CommonPool) { Log.d("TAG", "Start bg task") // Intentionally make bg task running for a long time SystemClock.sleep(2000) Log.d("TAG", "Throw bg task exception") throw RuntimeException("Bg task exception") } } catch (e: Exception) { Log.e("TAG", "Handle coroutine exception", e) } } launch(UI) { delay(1000) Log.d("TAG", "Cancel job = ${job.cancel()}") }
}
在AndroID上运行此功能会生成以下日志输出
07-26 15:09:10.038 31518-31518/co.foo.bar D/MainActivity: Start coroutine07-26 15:09:10.044 31518-31547/co.foo.bar D/MainActivity: Start bg task07-26 15:09:11.046 31518-31518/co.foo.bar D/MainActivity: Cancel job = true07-26 15:09:11.047 31518-31518/co.foo.bar E/MainActivity: Handled coroutine exception java.util.concurrent.CancellationException: Job was cancelled at kotlinx.coroutines.experimental.JobSupport$CompletedExceptionally.getException(Job.kt:921) at kotlinx.coroutines.experimental.runcompletion.afterCompletion(Builders.kt:198) ... at com.androID.internal.os.ZygoteInit.main(ZygoteInit.java:776)07-26 15:09:12.046 31518-31547/co.foo.bar D/MainActivity: Throwing bg task exception--------- beginning of crash07-26 15:09:12.046 31518-31547/co.foo.bar E/AndroIDRuntime: FATAL EXCEPTION: ForkJoinPool.commonPool-worker-1Process: co.foo.bar, PID: 31518 java.lang.RuntimeException: Bg task exception at co.foo.barsample.MainActivity$onCreate$job.doResume(MainActivity.kt:36) at kotlin.coroutines.experimental.jvm.internal.CoroutineImpl.resume(CoroutineImpl.kt:54) at kotlinx.coroutines.experimental.dispatchTask.run(Coroutinedispatcher.kt:120) at java.util.concurrent.ForkJoinTask$RunnableExecuteAction.exec(ForkJoinTask.java:1383) at java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:256) at java.util.concurrent.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1123) at java.util.concurrent.ForkJoinPool.scan(ForkJoinPool.java:1961) at java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1909) at java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:128)07-26 15:09:12.050 1705-2190/system_process W/ActivityManager: Force finishing activity co.foo.bar/co.foo.barsample.MainActivity
似乎是调用cancel()抛出了成功捕获的CancellationException.但是没有捕获后续的RuntimeException.我认为在取消作业后,以下异常应该被lib忽略?或者如何在不抛出CancellationException异常的情况下静默取消作业?
解决方法:
使用CoroutineExceptionHandler
作为additinoal coroutine上下文来处理异常,用于启动或运行
run(CommonPool + CoroutineExceptionHandler({ _, e -> Log.e("TAG", "CoroutineExceptionHandler", e)})) { ...}
要么
launch(UI + CoroutineExceptionHandler({ _, e -> Log.e("TAG", "CoroutineExceptionHandler", e)})) { ...}
总结 以上是内存溢出为你收集整理的android – Kotlin协程取消后无法捕获异常抛出全部内容,希望文章能够帮你解决android – Kotlin协程取消后无法捕获异常抛出所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)