Last active
September 12, 2018 11:56
-
-
Save mariodavid/4dfe204a25cc91d2a2d50b0b034d0a3d to your computer and use it in GitHub Desktop.
Groovy Closures with exceptions and return values
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import groovy.transform.InheritConstructors | |
def doIt(Closure whatToDo) { | |
println "hello in doIt" | |
def optionalResult = whatToDo.call() | |
println "after done it" | |
optionalResult | |
} | |
void callDoItWithException() { | |
try { | |
doIt { | |
println "my business logic" | |
throw new BreakoutOfClosureException("Oh no, a breakout happens") | |
println "successfull survived breakout" | |
} | |
} | |
catch (BreakoutOfClosureException e) { | |
println e.message | |
println "a breakout happend..." | |
} | |
} | |
int callItWithReturnValues() { | |
doIt { | |
return 5 | |
} | |
} | |
@InheritConstructors | |
class BreakoutOfClosureException extends RuntimeException {} | |
println "----------------" | |
println "Experiment 1: Exceptions" | |
callDoItWithException() | |
println "----------------" | |
println "Experiment 2: return values" | |
int resultOfCallItWithReturnValues = callItWithReturnValues() | |
println "the result is $resultOfCallItWithReturnValues" | |
println "----------------" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output