What if your program could tell you exactly what went wrong, every time?
Why Custom exception classes in Kotlin? - Purpose & Use Cases
Imagine you are building a program that handles different errors like invalid input, missing files, or network problems. Without custom exceptions, you have to guess what went wrong just by looking at generic error messages.
Using only built-in exceptions is like getting a vague "Something went wrong" message. It makes fixing problems slow and confusing because you can't tell exactly what caused the error or handle it properly.
Custom exception classes let you create clear, specific error types. This way, your program can catch and respond to each problem exactly as needed, making your code easier to understand and maintain.
try { // code that might fail } catch (e: Exception) { println("Error occurred") }
class InvalidInputException(message: String) : Exception(message) try { // code that might fail } catch (e: InvalidInputException) { println("Invalid input: ${e.message}") }
It enables your program to clearly communicate and handle different problems, making debugging and user feedback much better.
Think of a banking app that throws a specific exception when a withdrawal exceeds the balance. This helps the app show a clear message like "Insufficient funds" instead of a generic error.
Custom exceptions give clear, specific error types.
They help your program handle errors precisely.
This makes debugging and user messages easier and clearer.
Practice
Solution
Step 1: Understand what exceptions represent
Exceptions represent errors or unexpected events in a program.Step 2: Purpose of custom exceptions
Custom exceptions let you name specific error types clearly, making code easier to read and debug.Final Answer:
To define a specific type of error with a clear name -> Option BQuick Check:
Custom exceptions = clear error types [OK]
- Thinking custom exceptions fix errors automatically
- Believing they speed up code execution
- Confusing them with replacing built-in exceptions
MyError in Kotlin?Solution
Step 1: Recall Kotlin class declaration syntax
In Kotlin, classes are declared withclass ClassName.Step 2: Inherit from Exception class
Use colon:to inherit, soclass MyError : Exception()is correct.Final Answer:
class MyError : Exception() -> Option DQuick Check:
Custom exception syntax = class Name : Exception() [OK]
- Using 'fun' instead of 'class' to declare exception
- Using 'extends' or 'inherits' which are not Kotlin keywords
- Missing parentheses after Exception
class MyException : Exception("Custom error")
fun test() {
throw MyException()
}
fun main() {
try {
test()
} catch (e: MyException) {
println(e.message)
}
}Solution
Step 1: Understand the custom exception message
The class passes "Custom error" to Exception constructor, so e.message is "Custom error".Step 2: Catch block prints the exception message
The catch block catches MyException and prints e.message, which is "Custom error".Final Answer:
Custom error -> Option AQuick Check:
Exception message printed = Custom error [OK]
- Expecting class name instead of message
- Thinking program crashes without output
- Assuming message is null if not set explicitly
class MyException extends Exception() {}Solution
Step 1: Check Kotlin inheritance syntax
Kotlin uses colon ':' for inheritance, not 'extends'.Step 2: Identify the incorrect keyword
The code uses 'extends' which is from Java, causing syntax error.Final Answer:
Using 'extends' instead of ':' for inheritance -> Option CQuick Check:
Kotlin inheritance uses ':' not 'extends' [OK]
- Confusing Java syntax with Kotlin
- Thinking empty class body is invalid
- Believing Exception cannot be subclassed
InvalidAgeException that takes an age value as a property and shows a message like "Invalid age: 15". Which Kotlin code correctly implements this?Solution
Step 1: Understand primary constructor properties and string interpolation
In Kotlin,val param: Typecreates a read-only property accessible ase.age.Step 2: Constructor param available in super call
Params (with or without val) are in scope for superclass constructor, use$agefor interpolation (braces optional for simple identifiers).Step 3: Evaluate options
A correctly usesval age: Intfor property +$ageinterpolation. B/C/D lackval, so noageproperty (only private param). D uses concatenation (valid but less idiomatic).Final Answer:
class InvalidAgeException(val age: Int) : Exception("Invalid age: $age") -> Option AQuick Check:
val age: Int + $age interpolation for property + message [OK]
- Omitting 'val' (no public age property)
- Using unnecessary braces ${age} (optional for simple vars)
- Using string concatenation instead of interpolation
Ready to prove it?
Pass the test and this pattern moves unknown
