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