Exceptions in Coroutines
Siddhant Mishra
Senior Android Developer at Teachmint | Kotlin and Java | DSA - 300+ on Leetcode | I read and write about Android and DSA
Hi everyone, today I will be writing about exceptions in Coroutine and how to handle them gracefully.
First let us see some results to understand the exact issue -
Here, the code throws an unhandled exception after printing the "Inside the coroutine" statement. Let us try to handle it using usual try, catch -
The above works as expected since after printing the statement, it comes to the catch block and you can handle it subsequently.
Now let us look at using try and catch outside the launch -
It does not handle the exception as expected and will eventually crash the application -
Reason for the above - try and catch do not work over here because the exception inside is propagated to the parent level coroutine and it is not able to handle the uncaught exception. So in our application there might be instances where we launch a child coroutine inside a parent coroutine, and if the child coroutine throws exception then the parent coroutine is not able to handle it and it crashes the application. In this case we need to use CoroutineExceptionHandler -
Now using this, we can catch the exception but what happens when we want to continue with other children coroutines inside the runBlocking(Parent coroutine) even when one child coroutine throws an exception ?
In this case SupervisorScope comes to our rescue, using this we can continue with other children coroutines even when one child coroutine fails. It is useful when you want to go ahead with other apis even when one api fails. Check this -
I hope you got some insights regarding the exception handling in Coroutines. Do follow me for more such content. Happy coding.