dimsuz
06/14/2020, 8:29 PMlaunch {
try {
myCoroutine() // throws exception when executed
} catch (e: Exception) {
println("caught $e")
}
}
and instead of catching it crashes. But if I replace try/catch with
runCatching { myCoroutine() }.exceptionOrNull()?.let { println("caught $e") }
it catches and prints exception.
Now, myCoroutine
above involves calling android-related Retrofit library which has it's own coroutine adapters, so it might be doing some smarty stuff (debugger shows that continuation.resumeWithException()
is called, maybe on different dispatcher), but I want to understand in general the difference between try/catch
and `runCatching`: why can this situation happen and when I should use which approach to handling exceptions?octylFractal
06/14/2020, 8:34 PMThrowable
instead of Exception
?octylFractal
06/14/2020, 8:34 PMrunCatching
is literally a try
-`catch`:
public inline fun <R> runCatching(block: () -> R): Result<R> {
return try {
Result.success(block())
} catch (e: Throwable) {
Result.failure(e)
}
}
dimsuz
06/14/2020, 8:37 PMdimsuz
06/14/2020, 8:38 PMMarcelo Hernandez
06/15/2020, 4:29 AMCancellationException
gets thrown. However it will not cause a crash. If you catch Throwable
be sure to re-throw
it if it is an instance of CancellationException
so that the Coroutine cancels correctly. Otherwise you'll be treating the cancellation as is it were an actual error.Marcelo Hernandez
06/15/2020, 4:33 AMdimsuz
06/15/2020, 10:53 AMMarcelo Hernandez
06/16/2020, 1:39 AM