Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to catch an exception in Kotlin.
Android Kotlin
try { val result = 10 / 0 } catch (e: [1]) { println("Error occurred") }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using non-exception types like String or Int in catch.
✗ Incorrect
The Exception class is used to catch errors in Kotlin.
2fill in blank
mediumComplete the code to throw an exception when a condition is false.
Android Kotlin
fun checkAge(age: Int) {
if (age < 18) {
throw [1]("Age must be 18 or older")
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using unrelated exceptions like IOException for argument checks.
✗ Incorrect
IllegalArgumentException is used to indicate that a method has been passed an illegal or inappropriate argument.
3fill in blank
hardFix the error in the code to properly handle a nullable value with try-catch.
Android Kotlin
fun parseNumber(str: String?): Int {
return try {
str?.toInt() ?: throw [1]("Null string")
} catch (e: NumberFormatException) {
0
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Throwing unrelated exceptions like IOException for null checks.
✗ Incorrect
NullPointerException is appropriate to throw when a null value is unexpected.
4fill in blank
hardFill both blanks to create a try-catch block that logs the error message.
Android Kotlin
try { val data = fetchData() } catch (e: [1]) { Log.e("Error", e.[2]) }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using cause or stackTrace instead of message for error text.
✗ Incorrect
Catch Exception to handle errors, and use message to get the error description.
5fill in blank
hardFill all three blanks to define a custom exception class and throw it.
Android Kotlin
class [1](message: String) : [2](message) fun test() { throw [3]("Custom error") }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using Throwable directly or mismatching class names.
✗ Incorrect
Define a custom exception MyException that inherits from Exception and throw it.