Coroutine Exceptions & Error Handling Interview Questions

KOTLIN › Coroutines

How are exceptions handled differently in launch and async?

What a strong answer covers: In launch, an uncaught exception propagates to the parent straight away and, if nothing handles it, reaches the CoroutineExceptionHandler or crashes the app. In async the exception is stored in the Deferred and thrown when you call await(), but as a child of a regular scope it still cancels the parent immediately, even before await. So wrap await in try/catch and put async inside coroutineScope or supervisorScope deliberately.

What is a CoroutineExceptionHandler, and where does it have to be installed to work?

What a strong answer covers: It's a context element called for uncaught exceptions as a last resort, for logging or showing a generic error. It only works on root coroutines (launched directly in a scope) or direct children of a SupervisorJob; installed on a child coroutine it's ignored because the child passes the exception to its parent. It can't recover the coroutine: by then it has already completed.

What does SupervisorJob change, and what common mistake do people make with launch(SupervisorJob())?

What a strong answer covers: With a SupervisorJob, a child's failure doesn't cancel the parent or siblings. viewModelScope uses one, so one failed launch doesn't kill the others. The mistake is launch(SupervisorJob()) { launch { } } thinking it supervises the inner children: passing a Job to launch makes it the new coroutine's parent, so it breaks structured concurrency with the scope and the inner children still have a normal Job parent. Use supervisorScope instead.

Should a repository throw exceptions or return a Result type? How do you model errors from the network layer to the UI?

What a strong answer covers: A common approach: the data layer catches expected failures (IOException, HTTP errors) and maps them to a domain error or Result/sealed type, so the ViewModel handles them explicitly and the UI shows a specific state. Unexpected programming errors should still crash. Don't catch CancellationException. Trade-offs: exceptions are less boilerplate but invisible in signatures; Result types are explicit but need mapping at each layer.

Walk me through a crash you'd expect from this: viewModelScope.launch { val a = async { throw IOException() }; delay(1000); try { a.await() } catch (e: IOException) { } }. Why doesn't the try/catch save you?

What a strong answer covers: The async is a child of the launch coroutine with a normal Job. When it fails, it immediately cancels its parent, so the launch is cancelled during delay, before reaching the try/catch. The exception then reaches viewModelScope's SupervisorJob, and with no handler it goes to the thread's uncaught exception handler and crashes the app. Fixes: wrap the async in supervisorScope or coroutineScope inside a try/catch, or catch inside the async block.

Back to Coroutine Exceptions & Error Handling