-
Notifications
You must be signed in to change notification settings - Fork 22
Exception handling in async
Devrath edited this page Jan 16, 2024
·
3 revisions
- Here, When we invoke the
async
the exception is enclosed in the deferred and the exception is thrown when you call await.
Observation Program crashed
Output
Exception caught in main: java.lang.RuntimeException: Simulated exception in async task
FATAL EXCEPTION: main Process: com.istudio.app, PID: 16265 java.lang.RuntimeException: Simulated exception in async task
Code
class UsingAsyncExceptionHandleDemoVm @Inject constructor( ) : ViewModel() {
private val scopeJob = Job()
private val ourScope = CoroutineScope(scopeJob + Dispatchers.Default)
// <-----------------------> Using Exception Handler <------------------->
fun demo() {
val handler = CoroutineExceptionHandler { _, exception ->
println("Caught an exception: $exception")
}
viewModelScope.launch {
val deferredResult = async(handler) {
// Call the function that performs the asynchronous task
performAsyncTask()
}
try {
// Wait for the result of the async task
val result = deferredResult.await()
println("Async task result: $result")
} catch (e: Exception) {
// Exception will be caught by the exception handler
println("Exception caught in main: $e")
}
}
}
private suspend fun performAsyncTask(): String {
// Simulate some asynchronous work
delay(1000)
// Simulate an exception
throw RuntimeException("Simulated exception in async task")
}
// <-----------------------> Using Exception Handler <------------------->
}