📖 Scenario: Imagine you are writing a program that processes a simple task but you want to make sure some cleanup code always runs, no matter what happens during the task.
🎯 Goal: You will create a Kotlin program that uses a try, catch, and finally block to show how the finally block always runs.
📋 What You'll Learn
Create a variable called result and set it to an empty string
Add a try block that sets result to "Try block executed"
Add a catch block that sets result to "Catch block executed"
Add a finally block that appends " and Finally block executed" to result
Print the result variable
💡 Why This Matters
🌍 Real World
In real programs, <code>finally</code> blocks are used to close files, release resources, or clean up tasks that must happen no matter what.
💼 Career
Understanding <code>try</code>, <code>catch</code>, and <code>finally</code> is important for writing safe and reliable Kotlin applications, a key skill for many software development jobs.
Progress0 / 4 steps
1
Create the result variable
Create a variable called result and set it to an empty string "".
Kotlin
Hint
Use var result = "" to create an empty string variable.
2
Add the try block
Add a try block that sets result to "Try block executed".
Kotlin
Hint
Write try { result = "Try block executed" } to set the variable inside the try block.
3
Add the catch and finally blocks
Add a catch block that sets result to "Catch block executed" and a finally block that appends " and Finally block executed" to result.
Kotlin
Hint
Use catch (e: Exception) { result = "Catch block executed" } and finally { result += " and Finally block executed" }.
4
Print the result
Write println(result) to display the final value of result.
Kotlin
Hint
Use println(result) to show the output.
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
Step 1: Understand the role of finally
The finally block runs after try and catch, 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 A
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?