0
0
Kotlinprogramming~5 mins

Why error handling matters in Kotlin

Choose your learning style9 modes available
Introduction

Error handling helps your program deal with problems without crashing. It keeps your app working smoothly and lets you fix issues nicely.

When reading a file that might not exist
When asking for user input that could be wrong
When connecting to the internet which might fail
When dividing numbers and the divisor could be zero
When working with data that might be missing or wrong
Syntax
Kotlin
try {
    // code that might cause an error
} catch (e: Exception) {
    // code to handle the error
} finally {
    // code that runs no matter what
}

try block holds code that might cause an error.

catch block handles the error if it happens.

Examples
This tries to convert text to a number. If it fails, it prints a message.
Kotlin
try {
    val number = "abc".toInt()
} catch (e: NumberFormatException) {
    println("That is not a number!")
}
This catches the error when dividing by zero and shows a warning.
Kotlin
try {
    val result = 10 / 0
} catch (e: ArithmeticException) {
    println("Cannot divide by zero!")
}
Sample Program

This program tries to change text to a number. If it fails, it tells the user. It always prints a final message.

Kotlin
fun main() {
    val input = "hello"
    try {
        val number = input.toInt()
        println("Number is $number")
    } catch (e: NumberFormatException) {
        println("Oops! '$input' is not a number.")
    } finally {
        println("End of program.")
    }
}
OutputSuccess
Important Notes

Always handle errors to avoid program crashes.

Use finally to run code no matter what, like closing files.

Summary

Error handling keeps programs safe and user-friendly.

Use try and catch to manage problems.

Good error handling helps fix issues and keeps apps running.