Search⌘ K
AI Features

Solution: Exception Handling

Explore how to implement exception handling in Kotlin coroutines effectively. This lesson guides you through using try-catch blocks, managing coroutine cancellations, and coordinating concurrent tasks to ensure robust asynchronous code.

We'll cover the following...

Solution

The solution to the challenge we just solved is as follows.

suspend fun main() = supervisorScope {
   val str1 = async<String> {
       delay(2000)
       throw MyException()
   }

   val str2 = async {
       delay(2000)
       "Educative Inc."
   }

   try {
       println(str1.await())
   } catch (e: MyException) {
       println(e)
   }

   println(str2.await())
}
Complete code for the solution

Explanation

Here is a line–by–line ...