Kotlin 1.3.61
I have been reading the Effective Kotlin by Marcin Moskala book. And found the item on handling errors interesting as it discourages using a try-catch block and instead custom handler class
Quote from the book:
Using such error handling is not only more efficient than the try-catch block but often also easier to use and more explicit
However, there are cases where a try-catch cannot be avoided. I have the following snippet
class Branding {
fun createFormattedText(status: String, description: String): ResultHandler<PricingModel> {
return try {
val product = description.format(status)
val listProducts = listOf(1, 2, 3)
ResultHandler.Success(PricingModel(product, listProducts))
}
catch (exception: IllegalFormatException) {
ResultHandler.Failure(Throwable(exception))
}
}
}
class PricingModel(val name: String, products: List<Int>)
So the description.format(status) will throw an exception if it fails to format
This is my HandlerResult class, and what the book recommends:
sealed class ResultHandler<out T> {
class Success<out T>(val result: T) : ResultHandler<T>()
class Failure(val throwable: Throwable) : ResultHandler<Nothing>()
}
class FormatParsingException: Exception()
And how I use them in my code:
fun main() {
val branding = Branding()
val brand = branding.createFormattedText("status", "$%/4ed")
when(brand) {
is Success -> println(brand.result.name)
is Failure -> println(brand.throwable.message)
}
}
My question is. Is this one of those cases where a try-catch cannot be avoided. Or could I still return a Failure if the format was to fail while not use the try-catch?