Skip to content

Instantly share code, notes, and snippets.

@christo
Last active April 1, 2020 21:54
Show Gist options
  • Save christo/5441677 to your computer and use it in GitHub Desktop.
Save christo/5441677 to your computer and use it in GitHub Desktop.
Some compact Groovy syntax to ignore specific exceptions.
// you can make a construct for those
// times you want to ignore exceptions:
// here's the closure that can ignore things
def ignoring = { Class<? extends Throwable> catchMe, Closure callMe ->
try {
callMe.call()
} catch(e) {
if (!e.class.isAssignableFrom(catchMe)) {
throw e
}
}
}
// let's ignore a NumberFormatException
def i = 7
ignoring (NumberFormatException) {
i = Integer.parseInt("f")
}
assert i == 7
// ignore a NullPointerException, though none occur
ignoring (NullPointerException) {
i = Integer.parseInt("8")
}
assert i == 8
// unignored exceptions will still be thrown
try {
ignoring (NullPointerException) {
i = Integer.parseInt("f")
}
println 'unexpected failure to throw NumberFormatException'
} catch (NumberFormatException e) {
println "expected NumberFormatException was thrown"
}
println "i= ${i}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment