Member-only story

Exception Handling in Kotlin|try, catch, and finally

PINAR TURGUT
4 min readJan 23, 2024

In programming, sometimes unexpected things can happen, like trying to divide a number by zero or reading a file that doesn’t exist. Exception handling is like having a safety net to catch these unexpected situations. In Kotlin, we use try, catch, and finally to handle these situations.

fun divide(a: Int, b: Int): Int {
return try {
// Code that might cause an issue (e.g., division by zero)
a / b
} catch (e: ArithmeticException) {
// Code to handle the issue (e.g., print an error message)
-1
} finally {
// Code that always runs, whether there's an issue or not
}
}

fun main() {
// Calling the function
val result = divide(10, 2)
// Printing the result
println("Result: $result")
}

Explanation:

  • try block: It contains the code that might cause an issue, like dividing…

--

--

PINAR TURGUT
PINAR TURGUT

Written by PINAR TURGUT

Android developers who is passionate about personal growth https://pinartechtips.com

Responses (1)