0
0
Kotlinprogramming~10 mins

RunCatching for safe execution in Kotlin - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - RunCatching for safe execution
Start
RunCatching block
Try to execute code
Success?
YesReturn Success Result
Catch Exception
Return Failure Result
Use Result safely
End
RunCatching tries to run code safely, catching exceptions and returning a Result object that shows success or failure.
Execution Sample
Kotlin
val result = runCatching {
    val x = 10 / y
    "Result is $x"
}
println(result.getOrElse { "Error: ${it.message}" })
This code tries to divide 10 by y safely, catching any error and printing the result or error message.
Execution Table
StepActionEvaluationResult
1Enter runCatching blockStart code inside runCatchingNo result yet
2Evaluate 10 / yIf y=2, 10/2=55
3Create string "Result is 5"String formed"Result is 5"
4runCatching returns Success("Result is 5")Success resultSuccess("Result is 5")
5Call getOrElse on SuccessReturns success value"Result is 5"
6Print outputOutput to consoleResult is 5
7If y=0, division throws exceptionException caughtFailure(ArithmeticException)
8Call getOrElse on FailureReturns fallback string"Error: / by zero"
9Print outputOutput to consoleError: / by zero
💡 Execution stops after printing the result or error message.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4Final
y2 or 02 or 02 or 02 or 02 or 0
xundefined5 or exception5 or exception5 or exception5 or exception
resultundefinedundefinedundefinedSuccess or FailureSuccess or Failure
Key Moments - 3 Insights
Why does runCatching not crash the program when division by zero happens?
Because runCatching catches the exception inside its block and returns a Failure result instead of letting the exception crash the program (see steps 7 and 8 in execution_table).
What does getOrElse do with the Result object?
getOrElse returns the success value if present, or the fallback value if the Result is a failure (see steps 5 and 8 in execution_table).
Is the code inside runCatching executed immediately or deferred?
It is executed immediately when runCatching is called, but safely inside a try-catch block (see step 2 in execution_table).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'result' after step 4 when y=2?
ASuccess("Result is 5")
BFailure(ArithmeticException)
C"Result is 5"
DException thrown
💡 Hint
Check the 'Result' column at step 4 in execution_table.
At which step does runCatching catch an exception if y=0?
AStep 2
BStep 7
CStep 5
DStep 9
💡 Hint
Look for the step mentioning exception caught in execution_table.
If we change getOrElse fallback to "Oops", what will be printed when y=0?
A"Result is 5"
B"Error: / by zero"
C"Oops"
DProgram crashes
💡 Hint
Check step 8 and 9 in execution_table where getOrElse fallback is used.
Concept Snapshot
runCatching { code } runs code safely.
Returns Result: Success(value) or Failure(exception).
Use getOrElse { fallback } to get value or fallback.
Prevents crashes from exceptions inside block.
Ideal for safe error handling.
Full Transcript
RunCatching in Kotlin lets you run code that might fail without crashing your program. It tries to run the code inside its block. If the code works, it returns a Success result with the value. If the code throws an exception, runCatching catches it and returns a Failure result with the exception. You can then use getOrElse on the Result to get the success value or provide a fallback value if there was an error. This way, your program stays safe and you handle errors gracefully.