I found some documentation arguing about exception handling in Kotlin's coroutines with launch and async. But I could not found the solution dealing with the withContext.
suppose I have a coroutine like:
fun bar(path: String) {
viewModelScope.launch {
val foo = withContext(Dispatchers.IO) {
foo(path)
}
}
}
fun foo(path: String) {
// do something...
val media = MediaMetadataRetriever()
media.setDataSource(path) // may throw IllegalArgumentException according to API's doc
return media.frameAtTime
}
viewModelScope is imported from the lifecycle-viewmodel-ktx's implementation using a SupervisorJob.
Where should I put a try-catch block to deal with the IOException here?
try-catchin Kotlin is a code smell, unless it is in one of these helper functions. - Tenfour04withContextshould return a value. You should catch exception around your API call and makefoo()return failure/success object. Otherwise exception will be propagated aswithContextresult and you can catch it there. If you don't it's gonna be rethrown again and default exception handler oflaunchwill throw it as uncaught exception & your app will crash. - Pawel