Bird
Raised Fist0
Kotlinprogramming~20 mins

Custom exception classes in Kotlin - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Custom Exception Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2: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()
}
AException in thread "main" MyException: Oops!
BCaught: null
CCaught: Oops!
DCompilation error
Attempts:
2 left
💡 Hint
Look at how the exception message is passed and printed.
❓ Predict Output
intermediate
2: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)
}
Anull
BError
CPositive
DNegative
Attempts:
2 left
💡 Hint
Check what message the exception carries and how it's returned.
🔧 Debug
advanced
2: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")
}
AMissing primary constructor call to superclass Exception
Bsuper(message) cannot be called inside constructor body
CException class cannot be inherited
DNo error, code compiles and runs
Attempts:
2 left
💡 Hint
In Kotlin, superclass constructor must be called in constructor header.
📝 Syntax
advanced
2: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".
Aclass MyError(message: String = "Default error") : Exception(message)
Bclass MyError : Exception { constructor(message: String = "Default error") : super(message) }
Cclass MyError : Exception(message: String = "Default error")
Dclass MyError(message: String) : Exception { init { message = "Default error" } }
Attempts:
2 left
💡 Hint
Look for correct syntax for default parameter and superclass call.
🚀 Application
expert
2: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)
}
A2
B3
C1
D4
Attempts:
2 left
💡 Hint
Count only instances of CustomException class.

Practice

(1/5)
1. What is the main purpose of creating a custom exception class in Kotlin?
easy
A. To speed up program execution
B. To define a specific type of error with a clear name
C. To automatically fix errors in code
D. To replace all built-in exceptions

Solution

  1. Step 1: Understand what exceptions represent

    Exceptions represent errors or unexpected events in a program.
  2. Step 2: Purpose of custom exceptions

    Custom exceptions let you name specific error types clearly, making code easier to read and debug.
  3. Final Answer:

    To define a specific type of error with a clear name -> Option B
  4. Quick Check:

    Custom exceptions = clear error types [OK]
Hint: Custom exceptions give clear names to specific errors [OK]
Common Mistakes:
  • Thinking custom exceptions fix errors automatically
  • Believing they speed up code execution
  • Confusing them with replacing built-in exceptions
2. Which of the following is the correct way to declare a custom exception class named MyError in Kotlin?
easy
A. exception MyError extends Exception
B. fun MyError() : Exception
C. class MyError inherits Exception
D. class MyError : Exception()

Solution

  1. Step 1: Recall Kotlin class declaration syntax

    In Kotlin, classes are declared with class ClassName.
  2. Step 2: Inherit from Exception class

    Use colon : to inherit, so class MyError : Exception() is correct.
  3. Final Answer:

    class MyError : Exception() -> Option D
  4. Quick Check:

    Custom exception syntax = class Name : Exception() [OK]
Hint: Use colon : to inherit Exception in class declaration [OK]
Common Mistakes:
  • Using 'fun' instead of 'class' to declare exception
  • Using 'extends' or 'inherits' which are not Kotlin keywords
  • Missing parentheses after Exception
3. What will be the output of this Kotlin code?
class MyException : Exception("Custom error")

fun test() {
  throw MyException()
}

fun main() {
  try {
    test()
  } catch (e: MyException) {
    println(e.message)
  }
}
medium
A. Custom error
B. MyException
C. null
D. No output, program crashes

Solution

  1. Step 1: Understand the custom exception message

    The class passes "Custom error" to Exception constructor, so e.message is "Custom error".
  2. Step 2: Catch block prints the exception message

    The catch block catches MyException and prints e.message, which is "Custom error".
  3. Final Answer:

    Custom error -> Option A
  4. Quick Check:

    Exception message printed = Custom error [OK]
Hint: Exception message prints from e.message in catch block [OK]
Common Mistakes:
  • Expecting class name instead of message
  • Thinking program crashes without output
  • Assuming message is null if not set explicitly
4. Identify the error in this Kotlin custom exception class:
class MyException extends Exception() {}
medium
A. Class body cannot be empty
B. Missing parentheses after class name
C. Using 'extends' instead of ':' for inheritance
D. Exception class cannot be inherited

Solution

  1. Step 1: Check Kotlin inheritance syntax

    Kotlin uses colon ':' for inheritance, not 'extends'.
  2. Step 2: Identify the incorrect keyword

    The code uses 'extends' which is from Java, causing syntax error.
  3. Final Answer:

    Using 'extends' instead of ':' for inheritance -> Option C
  4. Quick Check:

    Kotlin inheritance uses ':' not 'extends' [OK]
Hint: Use ':' not 'extends' for inheritance in Kotlin [OK]
Common Mistakes:
  • Confusing Java syntax with Kotlin
  • Thinking empty class body is invalid
  • Believing Exception cannot be subclassed
5. You want to create a custom exception InvalidAgeException that takes an age value as a property and shows a message like "Invalid age: 15". Which Kotlin code correctly implements this?
hard
A. class InvalidAgeException(val age: Int) : Exception("Invalid age: $age")
B. class InvalidAgeException(age: Int) : Exception("Invalid age: ${age}")
C. class InvalidAgeException(age: Int) : Exception("Invalid age: $age")
D. class InvalidAgeException(age: Int) : Exception("Invalid age: " + age)

Solution

  1. Step 1: Understand primary constructor properties and string interpolation

    In Kotlin, val param: Type creates a read-only property accessible as e.age.
  2. Step 2: Constructor param available in super call

    Params (with or without val) are in scope for superclass constructor, use $age for interpolation (braces optional for simple identifiers).
  3. Step 3: Evaluate options

    A correctly uses val age: Int for property + $age interpolation. B/C/D lack val, so no age property (only private param). D uses concatenation (valid but less idiomatic).
  4. Final Answer:

    class InvalidAgeException(val age: Int) : Exception("Invalid age: $age") -> Option A
  5. Quick Check:

    val age: Int + $age interpolation for property + message [OK]
Hint: Use val age: Int and $age for property + message interpolation [OK]
Common Mistakes:
  • Omitting 'val' (no public age property)
  • Using unnecessary braces ${age} (optional for simple vars)
  • Using string concatenation instead of interpolation
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard