Bird
Raised Fist0
Kotlinprogramming~10 mins

Finally block behavior in Kotlin - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Finally block behavior
Try block starts
↓
Exception?
Yes→Catch block
↓
Catch block ends
↓
Try block ends
↓
Finally block
↓
Code after try-catch-finally
The finally block runs after try and catch blocks, no matter if an exception occurred or not.
Execution Sample
Kotlin
fun test() {
  try {
    println("Try block")
  } catch (e: Exception) {
    println("Catch block")
  } finally {
    println("Finally block")
  }
}
This code prints messages from try, catch (if exception), and finally blocks always.
Execution Table
StepActionException Thrown?Block ExecutedOutput
1Enter try blockNoTryTry block
2Try block completesNoTry
3No exception, skip catchNoCatch skipped
4Execute finally blockNoFinallyFinally block
5Exit functionNoEnd
💡 Try block finishes without exception, finally block runs, then function ends.
Variable Tracker
VariableStartAfter Step 1After Step 4Final
exceptionThrownfalsefalsefalsefalse
Key Moments - 3 Insights
Does the finally block run if there is no exception?
Yes, as shown in execution_table step 4, finally runs even when no exception occurs.
What happens if an exception is thrown in the try block?
The catch block runs first to handle it, then finally runs. This is shown in the flow diagram.
Can finally block change the return value or throw another exception?
Yes, finally runs last and can override return or throw new exceptions, but this example shows normal flow.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, which step shows the finally block running?
AStep 3
BStep 2
CStep 4
DStep 1
💡 Hint
Check the 'Block Executed' column for 'Finally' in execution_table row Step 4.
At which step does the program skip the catch block?
AStep 3
BStep 1
CStep 4
DStep 5
💡 Hint
Look at the 'Block Executed' column in execution_table where it says 'Catch skipped'.
If an exception was thrown in the try block, which block would run immediately after?
AFinally block
BCatch block
CTry block again
DFunction ends immediately
💡 Hint
Refer to the concept_flow diagram showing exception path from try to catch.
Concept Snapshot
try { ... } catch(e) { ... } finally { ... }
- finally always runs after try and catch
- runs even if no exception occurs
- can override return or throw new exceptions
- used for cleanup like closing files or releasing resources
Full Transcript
In Kotlin, the finally block runs after the try and catch blocks no matter what. If the try block runs without errors, the catch block is skipped, but finally still runs. If an exception happens, the catch block runs first, then finally. This ensures cleanup code always executes. The example code prints messages from try, catch (if needed), and finally blocks. The execution table shows step-by-step which block runs and when. Variables track if an exception occurred. Key moments clarify that finally runs always, even without exceptions, and can affect return values or throw new exceptions. The quiz tests understanding of when finally runs and the order of blocks during exceptions.

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