0
0
Kotlinprogramming~3 mins

Why Try-catch as an expression in Kotlin? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could catch errors and get results in one simple line of code?

The Scenario

Imagine you want to get a number from a text input and use it right away. You try to convert the text to a number, but sometimes the text is not a number at all. You have to write extra code to check if it worked or not.

The Problem

Without try-catch as an expression, you write long code with separate error handling. It makes your code bulky and hard to read. You might forget to handle errors properly, causing crashes or bugs.

The Solution

Try-catch as an expression lets you run code that might fail and immediately get a result or a fallback value. It makes your code shorter, cleaner, and easier to understand.

Before vs After
Before
var number: Int
try {
  number = input.toInt()
} catch (e: NumberFormatException) {
  number = 0
}
After
val number = try { input.toInt() } catch (e: NumberFormatException) { 0 }
What It Enables

You can write safer and simpler code that handles errors smoothly without extra steps.

Real Life Example

When reading user input for age, you can quickly convert it to a number or use zero if the input is invalid, all in one line.

Key Takeaways

Try-catch as an expression returns a value directly.

Makes error handling concise and readable.

Helps avoid crashes by providing fallback values easily.