0
0
Kotlinprogramming~10 mins

Why error handling matters in Kotlin - Test Your Understanding

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

Complete the code to catch an exception and print a message.

Kotlin
try {
    val result = 10 / [1]
    println("Result: $result")
} catch (e: Exception) {
    println("Error occurred")
}
Drag options to blanks, or click blank then click option'
A0
Bnull
C2
D10
Attempts:
3 left
💡 Hint
Common Mistakes
Using a non-zero number won't cause an error here.
2fill in blank
medium

Complete the code to throw an exception when input is negative.

Kotlin
fun checkNumber(num: Int) {
    if (num < [1]) {
        throw IllegalArgumentException("Negative number not allowed")
    }
}
Drag options to blanks, or click blank then click option'
A10
B1
C-1
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Using 1 or -1 changes the condition meaning.
3fill in blank
hard

Fix the error in the catch block to print the exception message.

Kotlin
try {
    val data = "abc".toInt()
} catch (e: Exception) {
    println(e[1])
}
Drag options to blanks, or click blank then click option'
A.message()
B.message
C.getMessage()
D.toString()
Attempts:
3 left
💡 Hint
Common Mistakes
Using parentheses causes a syntax error.
4fill in blank
hard

Fill both blanks to handle a NumberFormatException and print a custom message.

Kotlin
try {
    val num = "abc".toInt()
} catch (e: [1]) {
    println("[2]")
}
Drag options to blanks, or click blank then click option'
ANumberFormatException
BIllegalArgumentException
CNullPointerException
DArithmeticException
Attempts:
3 left
💡 Hint
Common Mistakes
Catching wrong exception types.
5fill in blank
hard

Fill all three blanks to create a function that safely parses an integer or returns null.

Kotlin
fun safeParseInt(str: String): Int? {
    return try {
        str[1]toInt()
    } catch (e: [2]) {
        [3]
    }
}
Drag options to blanks, or click blank then click option'
A.
BNumberFormatException
Cnull
D!!
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong exception type or returning wrong value.