Programming patterns for creating custom exceptions


#1

Hi all! I’m a Swift programmer, and in Swift there seems to be a common programming pattern for creating and throwing custom exceptions using an enum. For instance, if I’m writing a calculator app, it would go something like this:

enum CalculatorError: Error {
    case inputError(message: String)
    case invalidNumber(number: Int)
    case nilInput
    //...
}

class Calculator {
    func calculate(input: String) throws {
        //...
        throw CalculatorError.inputError(message: "This input is invalid!")
    }
}

Have you guys ever seen a pattern for custom exceptions show up in Kotlin? Maybe using data classes, maybe using sealed classes… I’m not really looking for a translation of this Swift code, rather I want something really Kotlin-y. I’d love to hear your thoughts :slight_smile:


#2

I have not really used or seen a pattern like this. One way to solve this would be just to create an abstract class and have each error extend this class or you could simply use a sealed class instead.
It kind of depends on what you want to this pattern to accomplish. If you just want a way to easily catch all different types of exceptions, than maybe an abstract parent class is the best solution.
On the other hand using a sealed class lets you easily use when expressions with type matching (you can use this as a statement only otherwise).
Also a sealed expression allows you to control the different types of exceptions. This could be handy in a big code base or in case of a library shared with other developers.