What if you could catch errors and get results in one simple line of code?
Why Try-catch as an expression in Kotlin? - Purpose & Use Cases
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.
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.
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.
var number: Int try { number = input.toInt() } catch (e: NumberFormatException) { number = 0 }
val number = try { input.toInt() } catch (e: NumberFormatException) { 0 }
You can write safer and simpler code that handles errors smoothly without extra steps.
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.
Try-catch as an expression returns a value directly.
Makes error handling concise and readable.
Helps avoid crashes by providing fallback values easily.