Challenge - 5 Problems
Custom Exception Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of custom exception throw and catch
What is the output of this Kotlin code that defines and throws a custom exception?
Kotlin
class MyException(message: String) : Exception(message) fun test() { try { throw MyException("Oops!") } catch (e: MyException) { println("Caught: ${e.message}") } } fun main() { test() }
Attempts:
2 left
💡 Hint
Look at how the exception message is passed and printed.
✗ Incorrect
The custom exception MyException inherits from Exception and passes the message. When thrown and caught, printing e.message shows "Oops!".
❓ Predict Output
intermediate2:00remaining
Value of variable after catching custom exception
What is the value of variable result after running this Kotlin code?
Kotlin
class CustomError(msg: String) : Exception(msg) fun checkValue(x: Int): String { return try { if (x < 0) throw CustomError("Negative") "Positive" } catch (e: CustomError) { e.message ?: "Error" } } fun main() { val result = checkValue(-5) println(result) }
Attempts:
2 left
💡 Hint
Check what message the exception carries and how it's returned.
✗ Incorrect
The function throws CustomError with message "Negative" for negative input, caught and returns the message.
🔧 Debug
advanced2:00remaining
Identify the error in custom exception class definition
This Kotlin code tries to define a custom exception but causes a compilation error. What is the error?
Kotlin
class BadException : Exception { constructor(message: String) { super(message) } } fun main() { throw BadException("Error") }
Attempts:
2 left
💡 Hint
In Kotlin, superclass constructor must be called in constructor header.
✗ Incorrect
In Kotlin, calling super(message) inside constructor body is invalid; it must be called in the constructor header.
📝 Syntax
advanced2:00remaining
Which option correctly defines a custom exception with default message?
Choose the Kotlin code that correctly defines a custom exception class with a default message "Default error".
Attempts:
2 left
💡 Hint
Look for correct syntax for default parameter and superclass call.
✗ Incorrect
Option A correctly uses default parameter and passes it to Exception superclass.
🚀 Application
expert2:00remaining
How many items in list after filtering custom exceptions?
Given this Kotlin code, how many exceptions in the list are instances of CustomException after filtering?
Kotlin
open class CustomException(msg: String) : Exception(msg) class AnotherException(msg: String) : Exception(msg) fun main() { val exceptions = listOf( CustomException("A"), AnotherException("B"), CustomException("C"), Exception("D") ) val filtered = exceptions.filter { it is CustomException } println(filtered.size) }
Attempts:
2 left
💡 Hint
Count only instances of CustomException class.
✗ Incorrect
Only two objects are instances of CustomException; others are different exception types.