在 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
但请记住,“不应使用异常进行流控制”,请特别参阅这个 Stack Overflow 问题:为什么不使用异常作为常规控制流?
因此,上述解决方案在任何情况下都不太理想。只需使用:
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