Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to print "Done" regardless of exceptions.
Kotlin
fun main() {
try {
println("Hello")
} finally {
println([1])
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Putting the print statement outside the finally block.
Using the wrong string inside println.
✗ Incorrect
The finally block always runs, so printing "Done" there ensures it prints regardless of exceptions.
2fill in blank
mediumComplete the code to catch an exception and still execute the finally block.
Kotlin
fun main() {
try {
val x = 10 / 0
} catch (e: [1]) {
println("Caught")
} finally {
println("Finally")
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Catching the wrong exception type.
Not including the finally block.
✗ Incorrect
Dividing by zero throws an ArithmeticException, so catching that allows the program to handle it and run finally.
3fill in blank
hardFix the error in the finally block to print "Cleanup".
Kotlin
fun main() {
try {
println("Start")
} finally {
println([1])
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Calling a function inside println incorrectly.
Missing quotes around the string.
✗ Incorrect
Inside println, you need a string literal "Cleanup". Using Cleanup() or Cleanup without quotes causes errors.
4fill in blank
hardFill both blanks to return a value from try and override it in finally.
Kotlin
fun test(): Int {
return try {
[1]
} finally {
[2]
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Not using return in finally to override.
Returning values without return keyword.
✗ Incorrect
Returning 1 in try is overridden by returning 2 in finally, so the function returns 2.
5fill in blank
hardFill all three blanks to print messages in try, catch, and finally blocks.
Kotlin
fun main() {
try {
println([1])
val x = 5 / 0
} catch (e: ArithmeticException) {
println([2])
} finally {
println([3])
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up messages in catch and finally.
Not printing anything in try before error.
✗ Incorrect
The try block prints "Trying", the catch prints "Caught Exception", and finally prints "Cleaning up".