2

In the book of "Functional programming in Scala", there are some words talk about the "checked exception":

Checked exceptions

Java’s checked exceptions at least force a decision about whether to handle or reraise 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:

def map[A,B](l: List[A])(f: A => B): List[B]

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.

I read this section several times, but still not clear why checked exception is not working for higher-order functions.

Could someone give some examples to make it more clear?

Community
  • 1
  • 1
Freewind
  • 193,756
  • 157
  • 432
  • 708

1 Answers1

6

Try to write the function map<A, B> in Java. At some point you'll find yourself needing to call your mapping function. Your mapping function could be anything and throw any kind of exception that it likes. The function map cannot include in its signature all the possible exceptions that the mapper can throw because it has no idea what it is. It's impossible to write the type signature of map with checked exceptions.

Suppose the signature of map was something like Colletion<B> map<A, B>(Function<A,B>, Collection<A>). Now suppose we call it as map(x -> throw new IOException, Lists.of(1,2,3)). Since IOException is checked, it should appear in the signature of map but until you called map, it had no idea that it could throw this type of exception.

tryx
  • 975
  • 7
  • 17