CodeBlanks Logo Icon CodeBlanks

finally

Learn the cleanup block with finally.

finally: the always-run block

The finally block always runs, whether or not an error occurs. It is ideal for closing resources or cleanup.

try {
    val x = 10 / 0
} catch (e: ArithmeticException) {
    println("Error")
} finally {
    println("Done")
}
// Error, Done

Even with an error, finally runs; that makes it safe for closing files or databases. It can be written without catch; then it only does cleanup. finally cannot be skipped.

finally and resource cleanup

After opening a resource you must close it. finally guarantees this even if an error occurs.

var open = true
try {
    // use resource
} finally {
    open = false  // always close
}

With or without an error, open = false runs. This prevents resource leaks. Even a return inside try still triggers the close in finally.

Practice Set up try-catch-finally

Inside a try block write val x = 10 / 0. Catch ArithmeticException and print "Error". Then in a finally block print "Done".

Starter code

Main.kt
fun main() {
    // Wrap a block in try-catch-finally; print Error and Done
}

Sample solution

Main.kt
fun main() {
    try {
        val x = 10 / 0
    } catch (e: ArithmeticException) {
        println("Error")
    } finally {
        println("Done")
    }
}

Expected output

Hata
Bitti

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match block to job

Term Meaning
try Trial block
catch Error catching
finally Always runs
throw Error raising

2 Fill in the blank: write finally

Question
try {
    val x = 1
} ____ {
    println("Done")
}
Answer
try {
    val x = 1
} finally {
    println("Done")
}

Explanation: the finally block always runs.

3 When does finally run?

  • Only when an error occurs
  • Always Correct answer
  • Only when no error
  • Never

Explanation: finally runs whether or not there is an error.

All lessons in Beginner