Groovy web console

subscribe to the feed Subscribe
to this
site
ignoring exceptions (via #groovywebconsole)
tweet this snippet Tweet
this
script

ignoring exceptions

Published 4 years ago by Chris Mountford with tags exceptions
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
// you can make a try { } catch (SomethingException e) { } construct for those times you want to ignore exceptions:

// here's the closure that can ignore things
def ignoring = { Class<? extends Throwable> exceptionToCatch, Closure callme ->
    try {
        callme.call()
    } catch(e) {        
        if (!e.class.isAssignableFrom(exceptionToCatch)) {
            throw e
        }
    }
}

// let's ignore a NumberFormatException
def i = 7
ignoring(NumberFormatException) {
    i = Integer.parseInt("f")
}
assert i == 7

// let's ignore a NullPointerException, though none occur
ignoring(NullPointerException) {
    i = Integer.parseInt("8")
}
assert i == 8

// now to show that exceptions which are not ignored will still be thrown
try {
    ignoring(NullPointerException) {
        i = Integer.parseInt("f")
    }
    println 'unexpected failure to throw NumberFormatException from parseInt("f")'
} catch (NumberFormatException e) {
    println "expected NumberFormatException was thrown"
}
println "i= ${i}"