0
0
Kotlinprogramming~5 mins

Try-catch as an expression in Kotlin

Choose your learning style9 modes available
Introduction

Try-catch as an expression lets you run code that might fail and immediately use the result or handle the error in one simple step.

When you want to get a value from code that might throw an error and use it right away.
When you want to keep your code clean by handling errors without extra lines.
When you want to assign a result from risky code directly to a variable.
When you want to provide a default value if something goes wrong.
When you want to avoid writing separate try and catch blocks for simple error handling.
Syntax
Kotlin
val result = try {
    // code that might throw
} catch (e: Exception) {
    // handle error and return a value
}

The try-catch block returns a value, so you can assign it directly to a variable.

The catch block must return the same type as the try block.

Examples
Convert a string to number, or use 0 if it fails.
Kotlin
val number = try {
    "123".toInt()
} catch (e: NumberFormatException) {
    0
}
Run a function that might fail, and return a message if it does.
Kotlin
val result = try {
    riskyOperation()
} catch (e: Exception) {
    "Error happened"
}
Sample Program

This program tries to convert a string to a number. If it fails, it uses -1 instead. Then it prints the result.

Kotlin
fun main() {
    val input = "abc"
    val number = try {
        input.toInt()
    } catch (e: NumberFormatException) {
        -1
    }
    println("The number is $number")
}
OutputSuccess
Important Notes

Try-catch as an expression helps keep your code short and clear.

Always make sure the catch block returns a value of the same type as the try block.

Summary

Try-catch can return a value, so you can assign it directly.

Use it to handle errors and provide fallback values simply.

This makes your code cleaner and easier to read.