Scala中finally块的返回值 [英] Return value of finally block in Scala
问题描述
可能的重复:
返回"和try-catch-finally"块评估斯卡拉
有两个 Scala 函数:
a): def foo(): Int = try { 1 } finally { 2 }
b): def bar(): Int = try { return 1 } finally { return 2}
我不明白为什么 foo
返回 1 而 bar
返回 2.
M.Odersky、L. Spoon 和 B.Venners 在Scala 编程"中解释了这种行为.我有第一版和第 7.5 节(第 128 页)说:
<块引用>值得注意的是,Scala 的行为与 Java 的不同只是因为 Java 的 try-finally
不会产生值.与在 Java 中一样,如果 finally
子句包含显式 return 语句或抛出异常,则该返回值或异常将推翻"源自 try 块或其 catch 子句之一的任何先前的值或异常.例如,给定:
def f(): Int = try { return 1 } finally { return 2 }
<块引用>
调用 f() 结果为 2.相比之下,给定:
def g(): Int = try { 1 } finally { 2 }
<块引用>
调用 g() 结果为 1.这两个函数都表现出令大多数程序员吃惊的行为,因此通常最好避免从 finally
子句中返回值.
<小时>
Scala 标准库具有 scala.util.control.Exception
API,提供用于处理异常的小型函数库.请参阅 scaladoc
Possible Duplicate:
"return" and "try-catch-finally" block evaluation in scala
There are two Scala functions:
a): def foo(): Int = try { 1 } finally { 2 }
b): def bar(): Int = try { return 1 } finally { return 2}
I cannot figure out why foo
returns 1 but bar
returns 2.
This behavior is explained in "Programming in Scala" by M.Odersky, L. Spoon and B.Venners. I have the first edition and section 7.5 (pg. 128) says:
it’s worth noting that Scala’s behavior differs from Java only because Java’s
try-finally
does not result in a value. As in Java, if afinally
clause includes an explicit return statement, or throws an exception, that return value or exception will "overrule" any previous one that originated in the try block or one of its catch clauses. For example, given:
def f(): Int = try { return 1 } finally { return 2 }
calling f() results in 2. By contrast, given:
def g(): Int = try { 1 } finally { 2 }
calling g() results in 1. Both of these functions exhibit behavior that could surprise most programmers, thus it's usually best to avoid returning values from
finally
clauses.
Scala standard library has scala.util.control.Exception
API that provides small functional library for handling exceptions. See the examples in scaladoc
这篇关于Scala中finally块的返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!