0
0
Kotlinprogramming~10 mins

Custom exception classes 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 define a custom exception class named MyException.

Kotlin
class MyException : [1]("Custom error occurred")
Drag options to blanks, or click blank then click option'
AException
BError
CThrowable
DRuntimeException
Attempts:
3 left
💡 Hint
Common Mistakes
Using Error instead of Exception as the base class.
Forgetting to extend any class.
2fill in blank
medium

Complete the code to throw the custom exception MyException.

Kotlin
fun checkValue(value: Int) {
    if (value < 0) {
        [1] MyException()
    }
}
Drag options to blanks, or click blank then click option'
Areturn
Bthrow
Craise
Derror
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'raise' which is from other languages.
Using 'return' which just exits the function.
3fill in blank
hard

Fix the error in the custom exception class constructor to accept a message parameter.

Kotlin
class MyException(message: String) : Exception([1]) {}
Drag options to blanks, or click blank then click option'
Amessage
B"message"
Cmsg
Dthis.message
Attempts:
3 left
💡 Hint
Common Mistakes
Passing a string literal instead of the variable.
Using an undefined variable name.
4fill in blank
hard

Fill both blanks to create a custom exception with a default message and a secondary constructor.

Kotlin
class MyException : Exception {
    constructor() : super([1])
    constructor(message: String) : super([2])
}
Drag options to blanks, or click blank then click option'
A"Default error"
Bmessage
C"Error occurred"
Dmsg
Attempts:
3 left
💡 Hint
Common Mistakes
Using undefined variable names.
Passing string literals where variables are expected.
5fill in blank
hard

Fill all three blanks to create a custom exception class with a message property and override the toString method.

Kotlin
class MyException(val [1]: String) : Exception([2]) {
    override fun toString(): String {
        return "MyException: " + [3]
    }
}
Drag options to blanks, or click blank then click option'
Amessage
Dmsg
Attempts:
3 left
💡 Hint
Common Mistakes
Using different names for the property and constructor parameter.
Not returning the message in toString.