How to Use Try Catch in Kotlin for Error Handling
In Kotlin, use
try and catch blocks to handle exceptions by wrapping code that might fail inside try and catching errors in catch. This prevents your program from crashing and lets you respond to errors gracefully.Syntax
The try block contains code that might throw an exception. The catch block handles the exception if it occurs. Optionally, a finally block runs code regardless of success or failure.
- try: Code that might cause an error.
- catch: Code to handle the error.
- finally: Code that always runs after try/catch.
kotlin
try { // code that may throw an exception } catch (e: ExceptionType) { // code to handle the exception } finally { // optional code that always runs }
Example
This example shows how to catch a division by zero error and print a message instead of crashing.
kotlin
fun main() {
val numerator = 10
val denominator = 0
try {
val result = numerator / denominator
println("Result: $result")
} catch (e: ArithmeticException) {
println("Cannot divide by zero!")
} finally {
println("Operation complete.")
}
}Output
Cannot divide by zero!
Operation complete.
Common Pitfalls
One common mistake is catching a general Exception without handling specific exceptions, which can hide bugs. Another is forgetting the try block around risky code, causing crashes. Also, avoid empty catch blocks that silently ignore errors.
kotlin
fun main() {
// Wrong: catching all exceptions without action
try {
val list = listOf(1, 2, 3)
println(list[5]) // Index out of bounds
} catch (e: Exception) {
// empty catch - error ignored
}
// Right: handle specific exception
try {
val list = listOf(1, 2, 3)
println(list[5])
} catch (e: IndexOutOfBoundsException) {
println("Index is out of range!")
}
}Output
Index is out of range!
Quick Reference
Remember these tips when using try catch in Kotlin:
- Use
tryto wrap code that might fail. - Catch specific exceptions to handle errors clearly.
- Use
finallyfor cleanup code that always runs. - Avoid empty
catchblocks to not hide problems.
Key Takeaways
Use try catch blocks to safely handle exceptions and prevent crashes.
Catch specific exceptions to respond properly to different errors.
The finally block runs code regardless of success or failure.
Avoid empty catch blocks that hide errors silently.
Always wrap risky code inside try to manage exceptions gracefully.