Last active
April 1, 2020 21:54
-
-
Save christo/5441677 to your computer and use it in GitHub Desktop.
Some compact Groovy syntax to ignore specific exceptions.
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
// 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