Kotlin-Coroutine Exception Handler

Sobhana kr
2 min readSep 28, 2022

--

Effective Way to handle Exceptions, instead of the routine way.

Basically, Coroutine Exception Handler is like plan B, when plan A fails to execute, we should have some backup to handle the situation.

Coroutine Exception Handler will prevent the crashes which may happen in the Apps when asynchronous tasks are going on, unhandled Exceptions will usually result as App Crashes.

General Pratice, every Android developer surely would have followed the method of simply adding a try-Catch Block, which will capture the exception.

try {Login(..)} catch (Exception e) {HandleException..}

Let us consider some Scenarios,

  1. Try block will hold the API call for Log- in in the Application.
  2. Catch block will capture the error thrown, while getting the exception from those code and it will Toast it or track it somehow.

Here, the Undefined Exceptions like 422.. Can be captured and tracked with the help of this Coroutine Exception Handler.

var coroutineExceptionHandler: CoroutineExceptionHandler ? = null
coroutineExceptionHandler = CoroutineExceptionHandler {
_,exception - >
if (exception is HttpException) {
// Handle the exception
}
}
viewModelScope.launch(Dispatchers.IO + coroutineExceptionHandler!!) {
LoginWithEmail(..)
}

If we get 422 Http Undefined Exception, we can attach it to Dispatcher to handle this scenario, if we get 200 response code, data will be loaded with LoadData(..) method and proceed successfully.

Try-Catch looks much simpler and easier compared to this Coroutine Exception Handler, but if we are going for two or more async calls involving Coroutines and If each one’s failure is non dependent of each other, for more Hierarchy level operations, this will be more useful to capture them, without being cancelled by Coroutines.

--

--