import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MaterialTheme {
Surface(modifier = Modifier.padding(16.dp)) {
CoroutineExceptionDemo()
}
}
}
}
}
@Composable
fun CoroutineExceptionDemo() {
var message by remember { mutableStateOf("") }
val coroutineScope = rememberCoroutineScope()
val handler = CoroutineExceptionHandler { _, exception ->
message = "Caught exception: ${exception.localizedMessage}"
}
Column {
Button(onClick = {
message = ""
coroutineScope.launch(handler) {
delay(500) // Simulate work
throw Exception("Something went wrong!")
// message = "Task completed successfully!" // This line won't run because of exception
}
}) {
Text("Start Coroutine")
}
Text(text = "Message: $message", modifier = Modifier.padding(top = 16.dp))
}
}
We create a CoroutineExceptionHandler that updates the message state when an exception occurs. The coroutine is launched with this handler, so if an exception is thrown inside, it is caught and the UI updates with the error message. This shows how to handle exceptions gracefully in coroutines and update the UI accordingly.