Challenge - 5 Problems
Finally Block Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of finally block with return in try
What is the output of this Kotlin code snippet?
Kotlin
fun test(): Int { try { return 1 } finally { println("Finally block executed") } } fun main() { println(test()) }
Attempts:
2 left
💡 Hint
Remember that finally block runs even if try returns.
✗ Incorrect
In Kotlin, the finally block always runs after the try block, even if the try block returns. So the println in finally executes before the returned value is printed.
❓ Predict Output
intermediate2:00remaining
Effect of exception and finally block
What will be printed when this Kotlin code runs?
Kotlin
fun test(): Int { try { throw Exception("Error") } finally { println("Finally block runs") } } fun main() { try { test() } catch (e: Exception) { println(e.message) } }
Attempts:
2 left
💡 Hint
Finally block runs even if exception is thrown.
✗ Incorrect
The exception is thrown in try, but before propagating, finally block runs and prints its message. Then the exception is caught in main and its message is printed.
🔧 Debug
advanced2:00remaining
Why does this finally block not execute?
Consider this Kotlin code. Why does the finally block not print anything?
Kotlin
fun test(): Int { try { System.exit(0) } finally { println("Finally block executed") } } fun main() { test() }
Attempts:
2 left
💡 Hint
System.exit stops the program immediately.
✗ Incorrect
System.exit(0) stops the whole program immediately, so the finally block is never reached or executed.
📝 Syntax
advanced2:00remaining
Identify the syntax error in finally usage
Which option contains a syntax error related to the finally block in Kotlin?
Attempts:
2 left
💡 Hint
Finally block must be a block, not a single statement without braces if catch is present.
✗ Incorrect
In Kotlin, if a finally block is present after a catch block, it must be a block enclosed in braces. Option D misses braces around finally block, causing syntax error.
🧠 Conceptual
expert2:00remaining
Finally block and variable modification with return
What is the output of this Kotlin code?
Kotlin
fun test(): Int { var x = 1 try { return x } finally { x = 2 println("Finally block: x = $x") } } fun main() { println("Returned value: ${test()}") }
Attempts:
2 left
💡 Hint
Return value is determined before finally block runs.
✗ Incorrect
The return value is evaluated before finally block runs, so it returns the original x=1. The finally block changes x to 2 and prints it, but this does not affect the returned value.