0
0
Android Kotlinmobile~5 mins

Error handling patterns in Android Kotlin

Choose your learning style9 modes available
Introduction

Error handling helps your app stay safe and friendly when something goes wrong. It stops crashes and shows helpful messages.

When reading data from the internet that might fail
When opening a file that might not exist
When converting user input to numbers
When calling a function that might throw an error
When working with databases that might have issues
Syntax
Android Kotlin
try {
    // code that might cause an error
} catch (e: ExceptionType) {
    // code to handle the error
} finally {
    // code that runs no matter what
}

try block contains code that might cause an error.

catch block handles the error if it happens.

Examples
This catches an error when converting text to a number.
Android Kotlin
try {
    val number = "abc".toInt()
} catch (e: NumberFormatException) {
    println("Not a valid number")
}
This handles errors when reading a file.
Android Kotlin
import java.io.File
import java.io.IOException

try {
    val file = File("path/to/file.txt")
    val text = file.readText()
} catch (e: IOException) {
    println("File not found or cannot read")
}
finally runs no matter if error happened or not.
Android Kotlin
try {
    val result = riskyOperation()
} catch (e: Exception) {
    println("Something went wrong")
} finally {
    println("This always runs")
}
Sample App

This program tries to convert a string to a number. If it fails, it shows an error message. It always prints a done message at the end.

Android Kotlin
fun main() {
    try {
        val input = "123a"
        val number = input.toInt()
        println("Number is $number")
    } catch (e: NumberFormatException) {
        println("Error: '$input' is not a number.")
    } finally {
        println("Done checking input.")
    }
}
OutputSuccess
Important Notes

Always catch specific exceptions to handle errors clearly.

Use finally to clean up resources like closing files or connections.

Don't ignore errors; show messages or fix problems to keep users happy.

Summary

Error handling keeps apps safe and user-friendly.

Use try-catch blocks to catch and fix errors.

finally runs code no matter what, useful for cleanup.