I have a code like this:
launch {
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?