0
0
Kotlinprogramming~10 mins

Multiple catch blocks 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 catch an exception of type ArithmeticException.

Kotlin
try {
    val result = 10 / 0
} catch (e: [1]) {
    println("Cannot divide by zero")
}
Drag options to blanks, or click blank then click option'
AArithmeticException
BIllegalArgumentException
CNullPointerException
DIOException
Attempts:
3 left
💡 Hint
Common Mistakes
Using IOException instead of ArithmeticException
Catching NullPointerException which is unrelated here
2fill in blank
medium

Complete the code to catch a NullPointerException.

Kotlin
val text: String? = null
try {
    println(text!!.length)
} catch (e: [1]) {
    println("Null value encountered")
}
Drag options to blanks, or click blank then click option'
AIndexOutOfBoundsException
BArithmeticException
CIOException
DNullPointerException
Attempts:
3 left
💡 Hint
Common Mistakes
Using ArithmeticException which is unrelated
Catching IOException which does not occur here
3fill in blank
hard

Fix the error in the catch block to handle IndexOutOfBoundsException.

Kotlin
val list = listOf(1, 2, 3)
try {
    println(list[5])
} catch (e: [1]) {
    println("Index is out of range")
}
Drag options to blanks, or click blank then click option'
AIndexOutOfBoundsException
BArithmeticException
CNullPointerException
DIllegalArgumentException
Attempts:
3 left
💡 Hint
Common Mistakes
Using NullPointerException which is unrelated
Catching ArithmeticException which does not occur here
4fill in blank
hard

Fill both blanks to catch ArithmeticException and NullPointerException separately.

Kotlin
try {
    val number = 10 / 0
    val text: String? = null
    println(text!!.length)
} catch (e: [1]) {
    println("Arithmetic error occurred")
} catch (e: [2]) {
    println("Null pointer error occurred")
}
Drag options to blanks, or click blank then click option'
AArithmeticException
BIOException
CNullPointerException
DIndexOutOfBoundsException
Attempts:
3 left
💡 Hint
Common Mistakes
Swapping the exception types
Using unrelated exceptions like IOException
5fill in blank
hard

Fill all three blanks to catch ArithmeticException, NullPointerException, and IndexOutOfBoundsException in separate catch blocks.

Kotlin
try {
    val result = 10 / 0
    val text: String? = null
    println(text!!.length)
    val list = listOf(1, 2, 3)
    println(list[5])
} catch (e: [1]) {
    println("Arithmetic error")
} catch (e: [2]) {
    println("Null pointer error")
} catch (e: [3]) {
    println("Index out of bounds error")
}
Drag options to blanks, or click blank then click option'
AArithmeticException
BNullPointerException
CIndexOutOfBoundsException
DIOException
Attempts:
3 left
💡 Hint
Common Mistakes
Using IOException which is unrelated
Mixing up the order of exceptions