0
0
Kotlinprogramming~5 mins

Finally block behavior in Kotlin - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
AAlways, after try and catch blocks
BOnly if an exception is thrown
COnly if no exception is thrown
DNever
What happens if there is a return statement in both try and finally blocks?
AThe return in finally block is ignored, try's return is used
BThe return in try block is ignored, finally's return is used
CBoth returns execute and return the sum
DCompilation error
If an exception is thrown in the finally block, what happens to an exception thrown in the try block?
ANo exception is thrown
BBoth exceptions are thrown together
CThe finally block's exception replaces the try block's exception
DThe try block's exception is thrown, finally's is ignored
Is the finally block mandatory in Kotlin's try-catch structure?
ANo, it's optional
BYes, always required
COnly if catch is present
DOnly if try block throws exception
Which of these is a good use case for a finally block?
AHandling specific exceptions
BReturning values
CDeclaring variables
DClosing a file 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.