paulmurray的回答後,我不知道自己會發生什麼從封閉中拋出的異常,所以我颳起了JUnit測試案例,很容易想到:
class TestCaseForThrowingExceptionFromInsideClosure {
@Test
void testEearlyReturnViaException() {
try {
[ 'a', 'b', 'c', 'd' ].each {
System.out.println(it)
if (it == 'c') {
throw new Exception("Found c")
}
}
}
catch (Exception exe) {
System.out.println(exe.message)
}
}
}
上面的輸出是:
a
b
c
Found c
但請記住,「一個不應使用流量控制例外」,具體見這個堆棧溢出問題:Why not use exceptions as regular flow of control?
所以上述方案小於在任何情況下的理想選擇。只需使用:
class TestCaseForThrowingExceptionFromInsideClosure {
@Test
void testEarlyReturnViaFind() {
def curSolution
[ 'a', 'b', 'c', 'd' ].find {
System.out.println(it)
curSolution = it
return (it == 'c') // if true is returned, find() stops
}
System.out.println("Found ${curSolution}")
}
}
以上的輸出也:
a
b
c
Found c