0
0
Kotlinprogramming~10 mins

Finally block behavior in Kotlin - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete 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'
A"Hello"
B"Done"
C"Error"
D"Try"
Attempts:
3 left
💡 Hint
Common Mistakes
Putting the print statement outside the finally block.
Using the wrong string inside println.
2fill in blank
medium

Complete 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'
AArithmeticException
BIOException
CNullPointerException
DException
Attempts:
3 left
💡 Hint
Common Mistakes
Catching the wrong exception type.
Not including the finally block.
3fill in blank
hard

Fix 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'
Aprintln("Cleanup")
BCleanup()
CCleanup
D"Cleanup"
Attempts:
3 left
💡 Hint
Common Mistakes
Calling a function inside println incorrectly.
Missing quotes around the string.
4fill in blank
hard

Fill 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'
A1
B2
Creturn 1
Dreturn 2
Attempts:
3 left
💡 Hint
Common Mistakes
Not using return in finally to override.
Returning values without return keyword.
5fill in blank
hard

Fill 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'
A"Trying"
B"Caught Exception"
C"Cleaning up"
D"Done"
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up messages in catch and finally.
Not printing anything in try before error.