Kotlin – Exception Handling (try-catch-finally): Write Safer, Crash-Free Code
Introduction – Why Learn Kotlin Exception Handling?
Every robust application needs to gracefully handle runtime errors—from invalid input to network failures. Kotlin inherits exception handling from Java and improves it with cleaner syntax, optional finally blocks, and powerful expression support.
In this guide, you’ll learn:
- How to use
try-catch-finallyin Kotlin - Catch multiple exceptions properly
- Handle exceptions as expressions
- Best practices to write crash-proof Kotlin apps
What Is Exception Handling?
Exception handling is a mechanism that allows you to catch and respond to errors during program execution—without crashing your app.
Basic try-catch Syntax in Kotlin
fun divide(a: Int, b: Int): Int {
return try {
a / b
} catch (e: ArithmeticException) {
println("Caught ArithmeticException: ${e.message}")
0
}
}
Usage:
val result = divide(10, 0)
println(result) // Output: 0
✔️ try block runs the risky code. If it fails, catch handles the exception.
Using finally Block
The finally block runs no matter what—even if an exception occurs or is caught.
fun openFile() {
try {
println("Opening file...")
throw Exception("File error")
} catch (e: Exception) {
println("Error: ${e.message}")
} finally {
println("Closing file...")
}
}
Output:
Opening file...
Error: File error
Closing file...
Catching Multiple Exceptions
You can use multiple catch blocks or handle multiple exceptions in one:
try {
// some code
} catch (e: IOException) {
println("IO Error")
} catch (e: NumberFormatException) {
println("Number Format Error")
}
✔️ Each block handles a specific exception type.
try as an Expression (Return Value)
In Kotlin, try-catch can return a value, just like an expression.
val number = try {
"123".toInt()
} catch (e: NumberFormatException) {
-1
}
println(number) // Output: 123
✔️ If no exception occurs, number = 123. If an exception occurs, fallback to -1.
Throwing Exceptions Manually
Use throw to explicitly raise exceptions.
fun validate(age: Int) {
if (age < 0) throw IllegalArgumentException("Age cannot be negative")
}
Checked vs Unchecked Exceptions
Kotlin does not enforce checked exceptions like Java. So, you’re not required to declare throws in function signatures.
fun risky() {
throw IOException("I/O Failed")
}
✔️ No need to write @Throws(IOException::class) unless using Java interop.
Common Mistakes
| Mistake | Fix |
|---|---|
| Swallowing all exceptions silently | Always log or handle exceptions meaningfully |
Using general catch (e: Exception) blindly | Be specific where possible (e.g., IOException) |
Forgetting finally for clean-up logic | Use finally to release resources (files, DB, etc.) |
| Returning null from try-catch silently | Prefer throwing or logging clear error messages |
Best Practices for Kotlin Exception Handling
| Practice | Benefit |
|---|---|
Use try as an expression | Cleaner, concise error fallback code |
| Always log or handle errors clearly | Easier to debug in production |
Use specific exceptions in catch | Avoids masking other bugs |
Release resources in finally | Prevents memory leaks or resource locks |
Summary – Recap & Next Steps
Exception handling in Kotlin is essential for building safe and reliable applications. With try-catch-finally, Kotlin offers clean, expressive, and powerful control over error scenarios.
Key Takeaways:
- Use
try-catchto catch runtime exceptions finallyalways runs—good for cleanup- Use
tryas an expression to assign fallback values - Be specific and meaningful when handling errors
Practical Use:
Kotlin exception handling is essential in file I/O, network requests, user input validation, and database operations across Android and server-side apps.
FAQs – Kotlin Exception Handling
Is try-catch-finally mandatory in Kotlin?
No. But it’s best practice to use it when there’s a risk of runtime exceptions (like file operations, parsing, etc.).
What is the purpose of the finally block?
It always runs—ideal for cleanup tasks like closing files, releasing locks, etc.
Can try-catch return a value in Kotlin?
Yes! It’s an expression. You can assign its result to a variable.
Is exception handling different in Kotlin vs Java?
Kotlin simplifies it. There’s no checked exception enforcement—you don’t need to declare throws.
How do I throw a custom exception in Kotlin?
Use the throw keyword:
throw IllegalStateException("Custom error")
Share Now :
