Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to throw an exception when the number is negative.
Kotlin
val number = -5 val result = if (number >= 0) number else throw [1]("Negative number")
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using println instead of throwing an exception
Trying to return a value instead of throwing
Using a non-exception class
✗ Incorrect
In Kotlin, you throw an exception using the 'throw' keyword followed by an exception class instance like IllegalArgumentException.
2fill in blank
mediumComplete the code to throw an exception as an expression inside a function.
Kotlin
fun getPositiveNumber(number: Int): Int = if (number > 0) number else throw [1]("Number must be positive")
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using println instead of throw
Using Error which is for serious system errors
Using Exception which is a checked exception in Java but less common in Kotlin
✗ Incorrect
Throwing RuntimeException is a common way to signal an error condition in Kotlin expressions.
3fill in blank
hardFix the error in the code by completing the throw expression correctly.
Kotlin
val value = 10 val result = if (value < 0) throw [1]("Negative value") else value
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using print instead of throw
Using return inside an expression
Trying to throw the throw keyword itself
✗ Incorrect
You must throw an exception object like IllegalStateException, not use print or return in this context.
4fill in blank
hardFill both blanks to throw an exception with a custom message when the input is zero.
Kotlin
fun checkInput(input: Int): Int {
return if (input != 0) input else throw [1]("Input cannot be zero: " + [2])
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a wrong variable name for the message
Throwing a generic RuntimeException without message
Not including the input value in the message
✗ Incorrect
Throw IllegalArgumentException with the input value to show the error message clearly.
5fill in blank
hardFill all three blanks to throw an exception as an expression inside a map operation.
Kotlin
val numbers = listOf(1, 2, 0, 4) val results = numbers.mapIndexed { [2], n -> if (n != 0) n else throw [1]("Zero found at index " + [2]) }.mapIndexed { [3], value -> value * 2 }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong variable names for index
Throwing generic exceptions without message
Confusing variable names in mapIndexed
✗ Incorrect
Throw IllegalStateException with the index variable in the message, and use 'i' as the index variable in mapIndexed.