Junior — Middle
launch funksiyasidan tashqarida joylashgan try/catch yordamida korutinlarni ishga tushirishda istisnolarni qanday boshqarish mumkin?
sobes.tech AI
AIdan javob
In Kotlin, the exceptions that occur inside coroutines cannot be caught with a regular try/catch if they are placed outside the launch function, because launch starts the coroutine asynchronously and immediately returns a Job object, and exceptions already occur in another context.
To handle exceptions, you need to use handlers inside the coroutine or special mechanisms:
- Use
CoroutineExceptionHandlerwhen creating the coroutine context. - Handle exceptions inside the coroutine with try/catch.
- For coroutines launched via
async, you can catch the exception when callingawait().
Example with CoroutineExceptionHandler:
val handler = CoroutineExceptionHandler { _, exception ->
println("Caught exception: ${exception.message}")
}
val job = CoroutineScope(Dispatchers.Default + handler).launch {
throw RuntimeException("Error in coroutine")
}
job.join()
Thus, try/catch outside launch will not work; you need to catch it inside the coroutine or use CoroutineExceptionHandler.