Bird
Raised Fist0
Kotlinprogramming~5 mins

Finally block behavior in Kotlin

Choose your learning style10 modes available
Introduction

The finally block lets you run code that must happen no matter what, like cleaning up or closing files.

You open a file and want to make sure it closes even if an error happens.
You start a network connection and want to close it no matter what.
You allocate resources and want to release them safely after use.
You want to print a message after trying some code, whether it worked or failed.
Syntax
Kotlin
try {
    // code that might throw an exception
} catch (e: Exception) {
    // code to handle the exception
} finally {
    // code that always runs
}

The finally block runs after try and catch, no matter what.

If there is a return statement in try or catch, finally still runs before returning.

Examples
This runs the try code and then always runs the finally block.
Kotlin
try {
    println("Trying something")
} finally {
    println("Always runs")
}
Even if an error happens and is caught, the finally block runs.
Kotlin
try {
    throw Exception("Oops")
} catch (e: Exception) {
    println("Caught: ${e.message}")
} finally {
    println("Cleanup")
}
The finally block runs before the function returns a value.
Kotlin
fun test(): String {
    try {
        return "From try"
    } finally {
        println("Finally runs before return")
    }
}

println(test())
Sample Program

This program tries to divide by zero, which causes an error. The catch block handles it, and the finally block runs no matter what. Then the program continues.

Kotlin
fun main() {
    try {
        println("Start try")
        val result = 10 / 0  // This causes an exception
        println("Result: $result")
    } catch (e: ArithmeticException) {
        println("Caught exception: ${e.message}")
    } finally {
        println("This always runs")
    }
    println("Program continues")
}
OutputSuccess
Important Notes

Use finally to keep your program safe by cleaning up resources.

If finally has a return statement, it can override returns from try or catch. Avoid this to prevent confusion.

Summary

The finally block always runs after try and catch.

It is useful for cleanup tasks like closing files or releasing resources.

Even if an exception happens or a return occurs, finally runs before the method exits.

Practice

(1/5)
1.

What is the main purpose of the finally block in Kotlin?

easy
A. To execute code that must run regardless of exceptions
B. To catch exceptions thrown in the try block
C. To declare variables used in try block
D. To stop program execution immediately

Solution

  1. Step 1: Understand the role of finally

    The finally block runs after try and catch, no matter what happens.
  2. Step 2: Identify its main use

    It is used to run cleanup code like closing files or releasing resources, always executing even if exceptions occur.
  3. Final Answer:

    To execute code that must run regardless of exceptions -> Option A
  4. Quick Check:

    finally always runs = A [OK]
Hint: Remember: finally always runs after try/catch [OK]
Common Mistakes:
  • Confusing finally with catch block
  • Thinking finally only runs if no exception
  • Believing finally stops program execution
2.

Which of the following is the correct syntax for a try-catch-finally block in Kotlin?

?
easy
A. catch (e: Exception) { /* handle */ } try { /* code */ } finally { /* cleanup */ }
B. try { /* code */ } finally { /* cleanup */ } catch (e: Exception) { /* handle */ }
C. try { /* code */ } catch { /* handle */ } finally { /* cleanup */ }
D. try { /* code */ } catch (e: Exception) { /* handle */ } finally { /* cleanup */ }

Solution

  1. Step 1: Recall Kotlin try-catch-finally order

    The correct order is try, then catch, then finally.
  2. Step 2: Check syntax correctness

    try { /* code */ } catch (e: Exception) { /* handle */ } finally { /* cleanup */ } follows the correct order and syntax with exception type in catch.
  3. Final Answer:

    try { /* code */ } catch (e: Exception) { /* handle */ } finally { /* cleanup */ } -> Option D
  4. Quick Check:

    try-catch-finally order = C [OK]
Hint: Remember order: try, catch, then finally [OK]
Common Mistakes:
  • Placing finally before catch
  • Omitting exception type in catch
  • Starting with catch block
3.

What will be the output of the following Kotlin code?

fun test(): Int {
    try {
        println("Try block")
        return 1
    } catch (e: Exception) {
        println("Catch block")
        return 2
    } finally {
        println("Finally block")
    }
}

fun main() {
    println("Result: ${test()}")
}
medium
A. Try block Finally block Result: 1
B. Try block Result: 1
C. Try block Catch block Finally block Result: 2
D. Finally block Result: 1

Solution

  1. Step 1: Trace the try block execution

    The try block prints "Try block" and returns 1, but before returning, finally runs.
  2. Step 2: Understand finally block behavior with return

    The finally block prints "Finally block" before the function returns the value 1.
  3. Final Answer:

    Try block Finally block Result: 1 -> Option A
  4. Quick Check:

    finally runs before return = A [OK]
Hint: finally runs even if return happens in try [OK]
Common Mistakes:
  • Ignoring finally output when return is in try
  • Assuming catch runs without exception
  • Thinking finally runs after return prints
4.

Identify the error in this Kotlin code snippet:

fun example() {
    try {
        println("Inside try")
    } finally {
        println("Inside finally")
    } catch (e: Exception) {
        println("Inside catch")
    }
}
medium
A. "catch" block must come before "finally" block
B. "finally" block must come after "catch" block
C. "catch" block cannot be used without "try"
D. No error, code is correct

Solution

  1. Step 1: Check order of try-catch-finally

    The correct order is try, then catch, then finally. Here finally comes before catch, which is invalid.
  2. Step 2: Identify correct placement

    The finally block must always come after all catch blocks.
  3. Final Answer:

    "finally" block must come after "catch" block -> Option B
  4. Quick Check:

    finally after catch = D [OK]
Hint: Catch comes before finally in try-catch-finally [OK]
Common Mistakes:
  • Placing finally before catch
  • Thinking catch can be after finally
  • Ignoring syntax order rules
5.

Consider this Kotlin function:

fun compute(): Int {
    try {
        return 10
    } finally {
        return 20
    }
}

What will compute() return and why?

hard
A. 10, because the first return in try is used
B. Compilation error due to multiple returns
C. 20, because finally's return overrides try's return
D. 0, because finally resets the return value

Solution

  1. Step 1: Analyze return in try block

    The try block returns 10, but before returning, finally executes.
  2. Step 2: Understand return in finally block

    The finally block also has a return statement, which overrides the previous return from try.
  3. Final Answer:

    20, because finally's return overrides try's return -> Option C
  4. Quick Check:

    Return in finally overrides try return = B [OK]
Hint: Return in finally overrides any previous return [OK]
Common Mistakes:
  • Assuming first return always wins
  • Thinking multiple returns cause error
  • Ignoring finally's effect on return
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard