Creating Custom Exception Classes
Define domain-specific exceptions with meaningful messages and properties.
Why Custom Exceptions?
Custom exceptions encode domain meaning: callers can catch them specifically, get useful messages, and act differently based on type.
Simplest Custom Exception
Subclass Exception (or a specific subclass like RuntimeException) and pass a message to the super constructor.
class InvalidEmailException(message: String) : Exception(message)
fun main() {
try {
throw InvalidEmailException("missing @")
} catch (e: InvalidEmailException) {
println("caught: ${e.message}")
}
}All lessons in this course
- try/catch/finally as an Expression
- Creating Custom Exception Classes
- runCatching and Result
- Re-throwing and Exception Chaining