0
0
KotlinHow-ToBeginner · 3 min read

How to Use finally in Kotlin: Syntax and Examples

In Kotlin, use the finally block after try and optional catch blocks to run code that must execute regardless of exceptions. The finally block is ideal for cleanup tasks like closing files or releasing resources.
📐

Syntax

The finally block follows try and optional catch blocks. It always runs whether an exception occurs or not.

  • try: Code that might throw an exception.
  • catch: Handles specific exceptions if thrown.
  • finally: Runs code that must execute after try/catch, like cleanup.
kotlin
try {
    // code that may throw an exception
} catch (e: Exception) {
    // handle exception
} finally {
    // code that always runs
}
💻

Example

This example shows how finally runs whether or not an exception happens. It prints messages to show the flow.

kotlin
fun main() {
    try {
        println("Trying to divide 10 by 0")
        val result = 10 / 0
        println("Result: $result")
    } catch (e: ArithmeticException) {
        println("Caught an exception: ${e.message}")
    } finally {
        println("This finally block always runs")
    }
    println("Program continues after try-catch-finally")
}
Output
Trying to divide 10 by 0 Caught an exception: / by zero This finally block always runs Program continues after try-catch-finally
⚠️

Common Pitfalls

One common mistake is assuming finally runs only if an exception occurs; it runs always. Another pitfall is returning a value inside finally, which can override exceptions or return values from try or catch, causing confusion.

Always avoid return statements inside finally to prevent unexpected behavior.

kotlin
fun testFinallyReturn(): Int {
    try {
        return 1
    } finally {
        return 2 // This overrides the try return, which is confusing
    }
}

fun main() {
    println(testFinallyReturn()) // Prints 2, not 1
}
Output
2
📊

Quick Reference

KeywordPurpose
tryWrap code that might throw exceptions
catchHandle specific exceptions thrown in try
finallyRun code always after try/catch, for cleanup

Key Takeaways

Use finally to run code that must execute regardless of exceptions.
Avoid return statements inside finally to prevent overriding returns or exceptions.
finally runs after try and catch blocks, even if no exception occurs.
Use finally for cleanup tasks like closing files or releasing resources.