Recall & Review
beginner
What is the purpose of the
finally block in Kotlin?The
finally block is used to execute code that must run regardless of whether an exception was thrown or caught. It is typically used for cleanup tasks like closing files or releasing resources.Click to reveal answer
beginner
When does the
finally block execute in Kotlin?The
finally block executes after the try and catch blocks finish, no matter if an exception occurred or not.Click to reveal answer
intermediate
Can the
finally block override a return statement in the try or catch block?Yes, if the
finally block contains a return statement, it will override any previous return from the try or catch blocks, which can lead to unexpected behavior.Click to reveal answer
advanced
What happens if an exception is thrown inside the
finally block?If an exception is thrown inside the
finally block, it will replace any exception thrown in the try or catch blocks, potentially hiding the original exception.Click to reveal answer
beginner
Write a simple Kotlin code snippet showing a
try-catch-finally structure.fun example() {
try {
println("In try block")
val result = 10 / 0 // This will throw an exception
} catch (e: ArithmeticException) {
println("Caught exception: ${e.message}")
} finally {
println("This runs no matter what")
}
}
Click to reveal answer
When does the
finally block run in Kotlin exception handling?✗ Incorrect
The finally block always runs after the try and catch blocks, regardless of exceptions.
What happens if there is a return statement in both try and finally blocks?
✗ Incorrect
The finally block's return overrides the try block's return, which can cause unexpected results.
If an exception is thrown in the finally block, what happens to an exception thrown in the try block?
✗ Incorrect
An exception in finally replaces any exception from try or catch blocks.
Is the finally block mandatory in Kotlin's try-catch structure?
✗ Incorrect
The finally block is optional and used only when cleanup or guaranteed execution is needed.
Which of these is a good use case for a finally block?
✗ Incorrect
Finally blocks are ideal for cleanup tasks like closing files or releasing resources.
Explain the role and behavior of the finally block in Kotlin exception handling.
Think about what must always happen after trying code, no matter what.
You got /5 concepts.
Describe what happens when a return statement is present in both try and finally blocks in Kotlin.
Consider which return value the function actually sends back.
You got /3 concepts.