Catching exceptions in coroutines
In this section, you will learn about coroutine exceptions and how to handle them in your application. As it is always possible that your coroutines will fail, it is important to learn how to catch exceptions so that you can avoid crashes and notify your users.
To handle exceptions in your coroutines, you can simply use try-catch
. For example, if you have a coroutine started with a launch
coroutine builder, you can do the following to handle exceptions:
class MovieViewModel: ViewModel() {
init {
viewModelScope.launch() {
try {
fetchMovies()
} catch (exception: Exception) {
...