Introduction
Exception handling in Kotlin lets you deal with runtime errors gracefully instead of letting the program crash. Kotlin uses the familiar try-catch-finally structure inherited from Java, but with an important twist: all exceptions in Kotlin are unchecked. This means the compiler never forces you to catch or declare an exception with a throws clause, giving developers more flexibility while placing the responsibility of anticipating failures squarely on them.
Cricket analogy: A batsman doesn't need to declare in advance that a yorker might dismiss him; like Kotlin's unchecked exceptions, no umpire forces him to formally declare risk before facing Bumrah's delivery, though a poor shot can still crash the innings.
Syntax
try {
// code that might throw an exception
} catch (e: SomeException) {
// handle the exception
} finally {
// always executed, cleanup code
}Explanation
The try block wraps code that could fail. If an exception is thrown, control jumps to the matching catch block, where the exception object 'e' can be inspected or logged. The finally block always runs, whether or not an exception occurred, making it ideal for closing resources. Unlike Java, Kotlin's try is an expression, meaning it can produce a value that gets assigned to a variable, with the last expression in the try or catch block becoming the result. Custom exceptions can be defined by extending Exception or RuntimeException.
Cricket analogy: The over itself is the try block facing risky deliveries; if Bumrah's yorker beats the bat, the umpire's raised finger is the catch inspecting what went wrong, the drinks break (finally) happens regardless of the dismissal, and a custom RunOutException could even be defined for that dismissal type.
Example
class InvalidAgeException(message: String) : Exception(message)
fun validateAge(age: Int): Int {
if (age < 0) throw InvalidAgeException("Age cannot be negative")
return age
}
fun main() {
val result = try {
validateAge(-5)
} catch (e: InvalidAgeException) {
println("Caught: ${e.message}")
-1
} finally {
println("Validation attempt finished")
}
println("Result: $result")
}
// Output:
// Caught: Age cannot be negative
// Validation attempt finished
// Result: -1Key Takeaways
- Kotlin uses try-catch-finally, similar in shape to Java's exception handling.
- All exceptions in Kotlin are unchecked; there is no throws keyword or forced catching.
- try is an expression in Kotlin and can return a value.
- finally always executes, making it ideal for resource cleanup.
- Custom exceptions extend Exception or RuntimeException.
Practice what you learned
1. What is a key difference between Kotlin and Java exception handling?
2. In Kotlin, what can a try block be used as?
3. Which block always executes regardless of whether an exception occurs?
4. How do you create a custom exception in Kotlin?
5. Does Kotlin require you to declare exceptions a function might throw?
Was this page helpful?
You May Also Like
Coroutines in Kotlin
Understand how Kotlin coroutines enable lightweight asynchronous programming using suspend functions and builders.
Kotlin-Java Interoperability
Explore how Kotlin and Java code can call each other seamlessly on the JVM, and the nuances that come with it.
Functions in Kotlin
Learn how to declare, call, and simplify functions in Kotlin, including single-expression syntax and the Unit type.
Common Kotlin Interview Questions
The Kotlin questions interviewers ask most, with concise, technically accurate answers you can defend under follow-up.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics