0
0
Kotlinprogramming~20 mins

RunCatching for safe execution in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
RunCatching for safe execution
📖 Scenario: Imagine you are writing a small Kotlin program that divides numbers. Sometimes, the divisor might be zero, which causes an error. You want to handle this safely without crashing the program.
🎯 Goal: You will build a Kotlin program that uses runCatching to safely execute a division operation and handle any errors gracefully.
📋 What You'll Learn
Create a function that divides two integers
Use runCatching to safely execute the division
Store the result or the error message
Print the final output showing success or failure
💡 Why This Matters
🌍 Real World
Handling errors safely is important in apps that deal with user input or external data, like calculators or data processors.
💼 Career
Many Kotlin jobs require writing robust code that does not crash on bad input. Using <code>runCatching</code> is a common way to handle exceptions cleanly.
Progress0 / 4 steps
1
Create a division function
Write a function called divide that takes two Int parameters named numerator and denominator. The function should return the result of dividing numerator by denominator as an Int.
Kotlin
Need a hint?

Use the / operator to divide the two integers inside the function.

2
Use runCatching to safely execute division
Create a variable called result that uses runCatching to call the divide function with 10 as numerator and 0 as denominator.
Kotlin
Need a hint?

Use runCatching { divide(10, 0) } to catch any exceptions from dividing by zero.

3
Extract success or failure message
Create a variable called message that uses result.fold to return the success value as a string or the failure exception message.
Kotlin
Need a hint?

Use fold on result to handle both success and failure cases.

4
Print the final message
Write a println statement to display the message variable.
Kotlin
Need a hint?

Use println(message) to show the result or error message.