This Kotlin Exception Handling tutorial explains how to handle runtime errors safely using try, catch, and finally blocks, and how to create and use custom exceptions. With clear examples and best practices, this chapter helps developers build robust and fault-tolerant Kotlin applications.
Kotlin Exception Handling – Complete Tutorial
What Is Exception Handling?
Exception handling allows a program to handle runtime errors gracefully without crashing the application.
try, catch, finally
Basic Syntax
try {
// risky code
} catch (e: Exception) {
// handle exception
} finally {
// always executes
}
Example: Handling Arithmetic Exception
fun main() {
try {
val result = 10 / 0
println(result)
} catch (e: ArithmeticException) {
println("Cannot divide by zero")
} finally {
println("Execution completed")
}
}
Multiple catch Blocks
try {
val number = "abc".toInt()
} catch (e: NumberFormatException) {
println("Invalid number format")
} catch (e: Exception) {
println("General exception")
}
Best Practices
- Catch specific exceptions first.
- Avoid catching generic
Exceptionunless necessary. - Use
finallyfor resource cleanup.
try as an Expression
In Kotlin, try can return a value.
fun main() {
val result = try {
"123".toInt()
} catch (e: NumberFormatException) {
0
}
println(result)
}
Custom Exceptions
Custom exceptions allow defining application-specific error conditions.
Creating a Custom Exception
class InvalidAgeException(message: String) : Exception(message)
Throwing a Custom Exception
fun validateAge(age: Int) {
if (age < 18) {
throw InvalidAgeException("Age must be 18 or above")
}
}
Using Custom Exception
fun main() {
try {
validateAge(15)
} catch (e: InvalidAgeException) {
println(e.message)
}
}
Best Practices for Custom Exceptions
- Extend
Exceptionor a specific subclass. - Provide meaningful error messages.
- Use custom exceptions for business logic errors.
Checked vs Unchecked Exceptions
- Kotlin does not have checked exceptions.
- All exceptions are unchecked and handled at runtime.
Best Practice
- Document exceptions clearly in function documentation.
Summary
This chapter explained Kotlin exception handling using try, catch, and finally, including handling multiple exceptions and using try as an expression. It also covered creating and using custom exceptions for application-specific error handling. Proper exception handling improves application reliability and maintainability.