concept exception in category kotlin

appears as: n exception, exceptions, exception, Exceptions, exception
Functional Programming with Kotlin

This is an excerpt from Manning's book Functional Programming with Kotlin.

  • Throwing an exception or halting with an error
  • We noted briefly in chapter 1 that throwing an exception is a side effect, and is undesired behaviour. But why do we consider throwing exceptions bad? Why is it not a desired effect? The answer has much to do with a loss of control. At the point that an exception is thrown, control is delegated away from the program, and the exception is propagated up the call stack. This loss of control means one of two things—the program will be terminated because the exception was not handled, or else some part of the program higher up on the call stack will catch and deal with the exception. The complexity of our program has just escalated dramatically, and in functional programming this loss of control and additional complexity should be avoided at all costs.

    If exceptions aren’t to be thrown in functional code, how do we deal with exceptional cases instead? The big idea is that we can represent failures and exceptions with ordinary values, and we can write higher-order functions that abstract out common patterns of error handling and recovery. The functional solution, of returning errors as values, is safer and retains referential transparency, and through the use of higher-order functions, we can preserve the primary benefit of exceptions—consolidation of error-handling logic. We’ll take a closer look at exceptions and discuss some of their problems, after which we will see how to deal with such cases using a functional approach.

    Java’s checked exceptions at least force a decision about whether to handle or re-raise an error, but they result in significant boilerplate for callers. More importantly, they don’t work for higher-order functions, which can’t possibly be aware of the specific exceptions that could be raised by their arguments. For example, consider the map function we defined for List:

    fun <A, B> map(xs: List<A>, f: (A) -> B): List<B> =
        foldRightL(xs, List.empty(), { a, xa -> Cons(f(a), xa) })

    This function is clearly useful, highly generic, and at odds with the use of checked exceptions—we can’t have a version of map for every single checked exception that could possibly be thrown by f. Even if we wanted to do this, how would map even know what exceptions were possible? This is why generic code, even in Java, so often resorts to using RuntimeException or some common checked Exception type.

    We’d like an alternative to exceptions without these drawbacks, but we don’t want to lose out on the primary benefit of exceptions: they allow us to consolidate and centralize error-handling logic, rather than being forced to distribute this logic throughout our codebase. The technique we use is based on an old idea: instead of throwing an exception, we return a value indicating that an exceptional condition has occurred. This idea might be familiar to anyone who has used return codes in C to handle exceptions. But instead of using error codes, we introduce a new generic type for these “possibly defined values” and use higher-order functions to encapsulate common patterns of handling and propagating errors. Unlike C-style error codes, the error-handling strategy we use is completely type-safe, and we get full assistance from the type-checker in forcing us to deal with errors, with a minimum of syntactic noise. We’ll see how all of this works shortly.

    The Joy of Kotlin

    This is an excerpt from Manning's book The Joy of Kotlin.

    Note that passing 0 and an empty list to this implementation wouldn’t cause an exception but would produce 0 as the result.

    In this chapter, you’ll work through a variety of exercises that teach you how to handle errors and exceptions in Kotlin. One skill you’ll learn is how to represent the absence of data due to an error, which the Option type doesn’t allow. We’ll first look at the problems that need solving, and then we’ll explore the Either type and the Result type:

    Whether you should handle exceptions or not depends on which function implementations you’ll use. If you use only your own implementations, you might not need to catch exceptions if you never throw one. But if you want to use functions from the standard library (which is likely), you need to deal with exceptions, applying the safe principle: always catch, never throw. Also note that you could be tempted to define the following function, as you did for Option:

    fun getOrElse(defaultValue: () -> A): A

    If you want to be sure to never throw an exception, you can’t implement this function. What would you return if the constant function () → A throws an exception?