Kotlin Exception Handling: Tame Errors in 2025
Four Key Players:
- π try: Wraps code that might throw an exception—must pair with catch or finally.
- π‘️ catch: Grabs exceptions tossed from try.
- ✅ finally: Runs no matter what—perfect for must-do tasks.
- π₯ throw: Lets you hurl a custom exception on purpose.
Unchecked Exceptions ⚠️
Unchecked exceptions sneak up due to coding slip-ups—extending the Exception class, checked at runtime. Examples include:
- π’ ArithmeticException: Dividing by zero.
- π ArrayIndexOutOfBoundsException: Bad array index.
- π SecurityException: Security rule breach.
- π NullPointerException: Calling methods on null.
Multiple Catch Blocks π‘️
Use multiple catch blocks to handle different exceptions from a try block:
fun main() {
try {
val a = IntArray(5)
a[5] = 10 / 0
} catch (e: ArithmeticException) {
println("arithmetic exception catch")
} catch (e: ArrayIndexOutOfBoundsException) {
println("array index outofbounds exception") // This runs
} catch (e: Exception) {
println("parent exception class")
}
}
Rules:
- π Only one catch runs per exception.
- π Order matters: Specific (e.g., ArithmeticException) before general (e.g., Exception).
Nested Try-Catch Blocks π‘️
Nest try-catch blocks when one risky operation might trigger another:
fun main() {
val nume = intArrayOf(4, 8, 16, 32, 64, 128, 256, 512)
val deno = intArrayOf(2, 0, 4, 4, 0, 8)
try {
for (i in nume.indices) {
try {
println("${nume[i]} / ${deno[i]} is ${nume[i] / deno[i]}")
} catch (exc: ArithmeticException) {
println("Can't divide by Zero!")
}
}
} catch (exc: ArrayIndexOutOfBoundsException) {
println("Element not found.")
}
}
Nested Notes:
- π‘️ Inner try catches division errors; outer catches array bounds.
- ⚡ Handles layered risks gracefully.
Finally Block ✅
The finally block runs always—exception or not—ideal for cleanup:
fun main() {
try {
val data = 10 / 5
println(data) // Outputs: 2
} catch (e: NullPointerException) {
println(e)
} finally {
println("finally block always executes") // Always runs
}
}
Finally Notes:
- ✅ Executes unless the program exits (e.g., via exitProcess).
- π§ Great for closing resources.
Throw Keyword π₯
Use throw to explicitly toss a custom exception:
fun main() {
validate(15)
println("code after validation check...")
}
fun validate(age: Int) {
if (age < 18)
throw ArithmeticException("under age") // Throws exception
else
println("eligible to drive")
}
Throw Notes:
- π₯ Custom error control—stop execution deliberately.
- ⚡ Paired with try-catch for handling.
Quick Comparison Table π€
A snapshot of exception handling keywords in Kotlin:
Keyword | Role | Key Features | Best Use Case |
---|---|---|---|
try | Risk Wrapper | Contains risky code | Testing operations |
catch | Exception Handler | Catches specific errors | Error recovery |
finally | Cleanup Crew | Always executes | Resource cleanup |
throw | Error Trigger | Throws custom exceptions | Manual error control |
Table Notes:
- π Role: What it does in handling.
- ⚡ Key Features: Unique traits.
- ✅ Best Use Case: When to use it.
..
Comments
Post a Comment