Skip to content

Instantly share code, notes, and snippets.

@mariodavid
Last active September 12, 2018 11:56
Show Gist options
  • Save mariodavid/4dfe204a25cc91d2a2d50b0b034d0a3d to your computer and use it in GitHub Desktop.
Save mariodavid/4dfe204a25cc91d2a2d50b0b034d0a3d to your computer and use it in GitHub Desktop.
Groovy Closures with exceptions and return values
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 "----------------"
@mariodavid
Copy link
Author

mariodavid commented Sep 12, 2018

Output

----------------
Experiment 1: Exceptions
hello in doIt
my business logic
Oh no, a breakout happens
a breakout happend...
----------------
Experiment 2: return values
hello in doIt
after done it
the result is 5
----------------

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment