0
0
Android Kotlinmobile~20 mins

Exception handling in coroutines in Android Kotlin - Mini App: Build & Ship

Choose your learning style9 modes available
Build: Coroutine Exception Handler Demo
This screen demonstrates how to handle exceptions in Kotlin coroutines by showing success or error messages.
Target UI
-------------------------
| Coroutine Exception    |
| Handler Demo          |
|-----------------------|
| [Start Coroutine]     |
|                       |
| Message:              |
|                       |
|                       |
|-----------------------|
Add a Button labeled 'Start Coroutine' that triggers a coroutine
Inside the coroutine, simulate a task that throws an exception
Use CoroutineExceptionHandler to catch the exception
Display the exception message in the Message area below the button
If no exception, display 'Task completed successfully!'
Starter Code
Android Kotlin
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.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()

  // TODO: Add CoroutineExceptionHandler here

  Column {
    Button(onClick = {
      // TODO: Launch coroutine with exception handling
    }) {
      Text("Start Coroutine")
    }

    Text(text = "Message: $message", modifier = Modifier.padding(top = 16.dp))
  }
}
Task 1
Task 2
Task 3
Task 4
Task 5
Solution
Android Kotlin
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.

Final Result
Completed Screen
-------------------------
| Coroutine Exception    |
| Handler Demo          |
|-----------------------|
| [Start Coroutine]     |
|                       |
| Message:              |
| Caught exception:     |
| Something went wrong! |
|-----------------------|
User taps 'Start Coroutine' button
Coroutine starts and throws an exception after a short delay
Exception is caught by CoroutineExceptionHandler
Message area updates to show 'Caught exception: Something went wrong!'
Stretch Goal
Modify the coroutine to sometimes complete successfully and sometimes throw an exception randomly.
💡 Hint
Use kotlin.random.Random.nextBoolean() inside the coroutine to decide whether to throw or complete.