RunCatching in Kotlin?runCatching is a Kotlin function that helps you run code safely by catching exceptions automatically. It wraps the code block and returns a Result object that holds either the success value or the exception.
RunCatching block?You can use getOrNull() to get the result if it succeeded, or null if there was an exception. Alternatively, use getOrElse { defaultValue } to provide a fallback value.
onFailure do when used with RunCatching?onFailure lets you run code only if the runCatching block caught an exception. It is useful for logging errors or handling failures without stopping the program.
RunCatching that safely divides two numbers and returns 0 if division fails.val result = runCatching { 10 / 0 }.getOrElse { 0 }
println(result) // Output: 0RunCatching preferred over traditional try-catch blocks?runCatching makes code cleaner and more readable by wrapping try-catch logic into a single expression. It also provides useful functions to handle success and failure in a functional style.
runCatching return after executing a block?runCatching returns a Result object that holds either the successful value or the caught exception.
getOrElse { default } returns the success value or the default if an exception occurred.
runCatching catches an exception?onFailure { } runs only if the block caught an exception.
runCatching { 5 / 0 }.getOrNull() return?Division by zero throws an exception, so getOrNull() returns null.
runCatching?runCatching does not fix bugs automatically; it only helps handle exceptions safely.
runCatching helps in safe execution of code in Kotlin.runCatching.