0
0
Kotlinprogramming~10 mins

Throw as an expression 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 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'
AExceptionHandler
Bprintln
Creturn
DIllegalArgumentException
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
2fill in blank
medium

Complete 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'
AError
BRuntimeException
CException
Dprintln
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
3fill in blank
hard

Fix 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'
AIllegalStateException
Bthrow
Creturn
Dprint
Attempts:
3 left
💡 Hint
Common Mistakes
Using print instead of throw
Using return inside an expression
Trying to throw the throw keyword itself
4fill in blank
hard

Fill 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'
AIllegalArgumentException
Binput
Cnumber
DRuntimeException
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
5fill in blank
hard

Fill 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'
AIllegalStateException
Bn
Cindex
Di
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong variable names for index
Throwing generic exceptions without message
Confusing variable names in mapIndexed