The finally block lets you run code that must happen no matter what, like cleaning up or closing files.
Finally block behavior in 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.
try code and then always runs the finally block.try { println("Trying something") } finally { println("Always runs") }
finally block runs.try { throw Exception("Oops") } catch (e: Exception) { println("Caught: ${e.message}") } finally { println("Cleanup") }
finally block runs before the function returns a value.fun test(): String { try { return "From try" } finally { println("Finally runs before return") } } println(test())
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.
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") }
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.
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
What is the main purpose of the finally block in Kotlin?
Solution
Step 1: Understand the role of
Thefinallyfinallyblock runs aftertryandcatch, no matter what happens.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.Final Answer:
To execute code that must run regardless of exceptions -> Option AQuick Check:
finallyalways runs = A [OK]
- Confusing finally with catch block
- Thinking finally only runs if no exception
- Believing finally stops program execution
Which of the following is the correct syntax for a try-catch-finally block in Kotlin?
?
Solution
Step 1: Recall Kotlin try-catch-finally order
The correct order istry, thencatch, thenfinally.Step 2: Check syntax correctness
try { /* code */ } catch (e: Exception) { /* handle */ } finally { /* cleanup */ } follows the correct order and syntax with exception type in catch.Final Answer:
try { /* code */ } catch (e: Exception) { /* handle */ } finally { /* cleanup */ } -> Option DQuick Check:
try-catch-finally order = C [OK]
- Placing finally before catch
- Omitting exception type in catch
- Starting with catch block
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()}")
}Solution
Step 1: Trace the try block execution
The try block prints "Try block" and returns 1, but before returning, finally runs.Step 2: Understand finally block behavior with return
The finally block prints "Finally block" before the function returns the value 1.Final Answer:
Try block Finally block Result: 1 -> Option AQuick Check:
finally runs before return = A [OK]
- Ignoring finally output when return is in try
- Assuming catch runs without exception
- Thinking finally runs after return prints
Identify the error in this Kotlin code snippet:
fun example() {
try {
println("Inside try")
} finally {
println("Inside finally")
} catch (e: Exception) {
println("Inside catch")
}
}Solution
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.Step 2: Identify correct placement
The finally block must always come after all catch blocks.Final Answer:
"finally" block must come after "catch" block -> Option BQuick Check:
finally after catch = D [OK]
- Placing finally before catch
- Thinking catch can be after finally
- Ignoring syntax order rules
Consider this Kotlin function:
fun compute(): Int {
try {
return 10
} finally {
return 20
}
}What will compute() return and why?
Solution
Step 1: Analyze return in try block
The try block returns 10, but before returning, finally executes.Step 2: Understand return in finally block
The finally block also has a return statement, which overrides the previous return from try.Final Answer:
20, because finally's return overrides try's return -> Option CQuick Check:
Return in finally overrides try return = B [OK]
- Assuming first return always wins
- Thinking multiple returns cause error
- Ignoring finally's effect on return
Ready to prove it?
Pass the test and this pattern moves unknown
