在《Functional programming in Scala》一书中,有这样一段话讲到“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.
这部分我读了好几遍,但仍然不清楚为什么已检查的异常不适用于高阶函数。
谁能举一些例子使它更清楚?
最佳答案
尝试编写函数map<A, B>
在 java 。在某些时候,您会发现自己需要调用映射函数。您的映射函数可以是任何 并抛出它喜欢的任何类型的异常。函数map
不能在其签名中包含映射器可能抛出的所有可能异常,因为它不知道它是什么。不可能写出 map
的类型签名有检查异常。
假设 map
的签名类似于 Colletion<B> map<A, B>(Function<A,B>, Collection<A>)
.现在假设我们称它为 map(x -> throw new IOException, Lists.of(1,2,3))
.自 IOException
被选中,它应该出现在map
的签名中但直到你调用map
,它不知道它可以抛出这种类型的异常。
关于scala - 不清楚 "Checked exception"中的 "functional programming in Scala"解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31402608/