Kotlin Exception Handling: Tame Errors in 2025

An exception is a runtime hiccup—like running out of memory, hitting an array out-of-bounds error, or dividing by zero—that can crash your program. Exception handling steps in to keep things flowing smoothly! 🌟

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

Popular posts from this blog

Creating Beautiful Card UI in Flutter

Master Web Development with Web School Offline

Jetpack Compose - Card View