Bird
Raised Fist0
Android Kotlinmobile~20 mins

Error handling patterns in Android Kotlin - Mini App: Build & Ship

Choose your learning style10 modes available
Build: Error Handling Demo
This screen demonstrates common error handling patterns in Kotlin for Android. It shows how to handle errors from a simulated network call and display messages to the user.
Target UI
-------------------------
| Error Handling Demo    |
|-----------------------|
| [Fetch Data]          |
|                       |
| Status:               |
|                       |
| Message:              |
-------------------------
Add a button labeled 'Fetch Data' that triggers a simulated network call.
Simulate success or failure randomly when fetching data.
Use try-catch to handle exceptions from the simulated call.
Display 'Status: Success' or 'Status: Error' accordingly.
Show the error message if an error occurs.
Use Kotlin's runCatching or Result type to demonstrate another error handling pattern.
Ensure UI updates happen on the main thread.
Starter Code
Android Kotlin
package com.example.errorhandlingdemo

import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import kotlin.random.Random

class MainActivity : AppCompatActivity() {
    private lateinit var statusTextView: TextView
    private lateinit var messageTextView: TextView
    private lateinit var fetchButton: Button

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        statusTextView = findViewById(R.id.statusTextView)
        messageTextView = findViewById(R.id.messageTextView)
        fetchButton = findViewById(R.id.fetchButton)

        fetchButton.setOnClickListener {
            // TODO: Implement error handling when fetching data
        }
    }

    // Simulate a network call that randomly succeeds or throws an exception
    private fun fetchData(): String {
        if (Random.nextBoolean()) {
            return "Data loaded successfully"
        } else {
            throw Exception("Network error occurred")
        }
    }
}
Task 1
Task 2
Task 3
Task 4
Solution
Android Kotlin
package com.example.errorhandlingdemo

import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import kotlin.random.Random

class MainActivity : AppCompatActivity() {
    private lateinit var statusTextView: TextView
    private lateinit var messageTextView: TextView
    private lateinit var fetchButton: Button
    private var useRunCatching = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        statusTextView = findViewById(R.id.statusTextView)
        messageTextView = findViewById(R.id.messageTextView)
        fetchButton = findViewById(R.id.fetchButton)

        fetchButton.setOnClickListener {
            if (useRunCatching) {
                fetchDataWithRunCatching()
            } else {
                fetchDataWithTryCatch()
            }
            useRunCatching = !useRunCatching
        }
    }

    private fun fetchDataWithTryCatch() {
        try {
            val data = fetchData()
            statusTextView.text = "Status: Success"
            messageTextView.text = data
        } catch (e: Exception) {
            statusTextView.text = "Status: Error"
            messageTextView.text = e.message
        }
    }

    private fun fetchDataWithRunCatching() {
        val result = runCatching { fetchData() }
        result.onSuccess { data ->
            statusTextView.text = "Status: Success"
            messageTextView.text = data
        }.onFailure { error ->
            statusTextView.text = "Status: Error"
            messageTextView.text = error.message
        }
    }

    private fun fetchData(): String {
        if (Random.nextBoolean()) {
            return "Data loaded successfully"
        } else {
            throw Exception("Network error occurred")
        }
    }
}

This solution shows two common error handling patterns in Kotlin for Android.

First, try-catch is used in fetchDataWithTryCatch() to catch exceptions from fetchData(). If successful, it updates the UI with success status and data. If an exception occurs, it shows an error status and message.

Second, runCatching is used in fetchDataWithRunCatching(). This Kotlin function wraps the call and returns a Result object. We then use onSuccess and onFailure to handle success and error cases cleanly.

The button toggles between these two methods each time it is clicked, demonstrating both patterns in one screen.

UI updates happen on the main thread because the click listener runs on the main thread by default.

Final Result
Completed Screen
-------------------------
| Error Handling Demo    |
|-----------------------|
| [Fetch Data]          |
|                       |
| Status: Success       |
|                       |
| Message:              |
| Data loaded successfully|
-------------------------
User taps 'Fetch Data' button.
App randomly succeeds or fails to fetch data.
If success, 'Status: Success' and success message appear.
If failure, 'Status: Error' and error message appear.
Each tap toggles between try-catch and runCatching error handling.
Stretch Goal
Add a toggle switch to let the user choose between try-catch and runCatching error handling methods.
💡 Hint
Use a Switch or ToggleButton widget and update the fetch method based on its state.

Practice

(1/5)
1. What is the main purpose of a try-catch block in Kotlin error handling?
easy
A. To style the user interface
B. To speed up the app execution
C. To create new variables
D. To catch exceptions and prevent app crashes

Solution

  1. Step 1: Understand the role of try-catch

    The try block contains code that might cause an error, and the catch block handles that error.
  2. Step 2: Identify the purpose in app safety

    Using try-catch prevents the app from crashing by catching exceptions and allowing graceful handling.
  3. Final Answer:

    To catch exceptions and prevent app crashes -> Option D
  4. Quick Check:

    Error handling = catch exceptions [OK]
Hint: Try-catch blocks catch errors to keep apps running [OK]
Common Mistakes:
  • Thinking try-catch speeds up code
  • Confusing try-catch with UI styling
  • Believing try-catch creates variables
2. Which of the following is the correct syntax to catch an exception in Kotlin?
easy
A. try { /* code */ } catch e { /* handle */ }
B. try { /* code */ } except (e: Exception) { /* handle */ }
C. try { /* code */ } catch (e: Exception) { /* handle */ }
D. try { /* code */ } catch Exception e { /* handle */ }

Solution

  1. Step 1: Recall Kotlin catch syntax

    Kotlin requires parentheses around the exception variable with its type in the catch block.
  2. Step 2: Compare options to correct syntax

    Only try { /* code */ } catch (e: Exception) { /* handle */ } uses catch (e: Exception) which is the correct Kotlin syntax.
  3. Final Answer:

    try { /* code */ } catch (e: Exception) { /* handle */ } -> Option C
  4. Quick Check:

    Correct catch syntax = try { /* code */ } catch (e: Exception) { /* handle */ } [OK]
Hint: Catch needs parentheses with exception type [OK]
Common Mistakes:
  • Omitting parentheses in catch
  • Using 'except' instead of 'catch'
  • Wrong order of exception and variable
3. What will be the output of this Kotlin code?
fun main() {
  try {
    val result = 10 / 0
    println("Result: $result")
  } catch (e: ArithmeticException) {
    println("Caught an arithmetic error")
  } finally {
    println("Done")
  }
}
medium
A. Caught an arithmetic error\nDone
B. Done
C. Exception thrown, app crashes
D. Result: 0\nDone

Solution

  1. Step 1: Identify the error in try block

    Dividing 10 by 0 causes an ArithmeticException.
  2. Step 2: Check catch and finally behavior

    The catch block catches the exception and prints the message. The finally block always runs and prints "Done".
  3. Final Answer:

    Caught an arithmetic error\nDone -> Option A
  4. Quick Check:

    Catch runs on error, finally always runs [OK]
Hint: Catch handles error, finally always runs [OK]
Common Mistakes:
  • Assuming division by zero prints result
  • Ignoring finally block output
  • Thinking app crashes without catch
4. Identify the error in this Kotlin code snippet:
try {
  val text: String = null
  println(text.length)
} catch (e: NullPointerException) {
  println("Null pointer caught")
}
medium
A. Code will not compile due to null assignment
B. Accessing length of null causes a crash
C. NullPointerException is not caught correctly
D. No error, code runs fine

Solution

  1. Step 1: Analyze null assignment in Kotlin

    Kotlin does not allow assigning null to a non-nullable type without using nullable type syntax.
  2. Step 2: Check compilation rules

    Assigning null to val text without declaring it nullable causes a compile-time error.
  3. Final Answer:

    Code will not compile due to null assignment -> Option A
  4. Quick Check:

    Null safety requires nullable types [OK]
Hint: Null must be assigned to nullable type with ? [OK]
Common Mistakes:
  • Assuming NullPointerException is caught at runtime
  • Ignoring Kotlin's null safety rules
  • Thinking code runs without error
5. You want to read a file and always close it after reading, even if an error occurs. Which Kotlin error handling pattern is best to ensure the file closes properly?
hard
A. Use try block only
B. Use try-catch-finally and close file in finally
C. Use try-catch without finally
D. Use only finally block

Solution

  1. Step 1: Understand resource cleanup needs

    Files must be closed to free resources, even if an error happens during reading.
  2. Step 2: Use finally block for guaranteed execution

    The finally block runs no matter what, so closing the file there ensures cleanup.
  3. Step 3: Combine with try-catch for error handling

    Try-catch handles errors, finally ensures file closure regardless of success or failure.
  4. Final Answer:

    Use try-catch-finally and close file in finally -> Option B
  5. Quick Check:

    Finally block ensures cleanup [OK]
Hint: Put cleanup code in finally block to always run [OK]
Common Mistakes:
  • Closing file only in try block
  • Ignoring finally block for cleanup
  • Using finally without try-catch
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard