0
0
Kotlinprogramming~15 mins

Try-catch as an expression in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
Try-catch as an expression
📖 Scenario: Imagine you are writing a small Kotlin program that tries to convert user input into a number. Sometimes the input might not be a valid number, so you want to handle that error smoothly.
🎯 Goal: You will build a Kotlin program that uses try-catch as an expression to safely convert a string to an integer. If the conversion fails, it will return a default value.
📋 What You'll Learn
Create a variable with a string that might not be a number
Create a default integer value for fallback
Use try-catch as an expression to convert the string to an integer or use the default
Print the final integer value
💡 Why This Matters
🌍 Real World
Handling user input or data from files where the format might be incorrect is common. Using try-catch as an expression helps keep code clean and safe.
💼 Career
Many Kotlin jobs require safe error handling and working with user input or external data. This skill is essential for writing robust applications.
Progress0 / 4 steps
1
Create the input string
Create a variable called input and set it to the string "abc123".
Kotlin
Need a hint?

Use val input = "abc123" to create the string variable.

2
Create the default fallback value
Create a variable called defaultValue and set it to the integer 0.
Kotlin
Need a hint?

Use val defaultValue = 0 to create the fallback integer.

3
Use try-catch as an expression to convert input
Create a variable called number and set it to the result of a try-catch expression that tries to convert input to an integer using input.toInt(). If an exception occurs, return defaultValue.
Kotlin
Need a hint?

Use val number = try { input.toInt() } catch (e: Exception) { defaultValue } to handle conversion safely.

4
Print the result
Write a println statement to display the value of number.
Kotlin
Need a hint?

Use println(number) to show the final integer.