23 April 2013

Nice Syntax for Ignoring Exceptions in Groovy

Save your breath. I don't need to hear how we shouldn't ignore exceptions. I agree with you. We should use exceptions as a part of an API and we should accept exception handling as an important, fundamental design element in our code. Happy?

OK now, sometimes you know you need to ignore an exception. Often it's a narrow exception type, for example, the following exceptions are frequently ignored with good reason (usually the exception cannot happen in practice):

MalformedURLException
NumberFormatException
IllegalAccessException
UnsupportedEncodingException

Groovy inherits Java's exception handling syntax, the try, catch, finally blocks. While writing some code that ignored the exceptions I wondered what a Groovier way to do things would be. The following Config class is a kind of bean containing validated values read from a properties file. The defaults remain if the config file cannot be parsed for the given value.


Notice how the try {...} catch {...} looks like Groovy's closure passing syntax, as if there was a try method which is being passed a block. In fact I think Scala's equivalent is literally this (also, Scala is awesome). 

But while it looks that way, it doesn't quite act that way. 

But could it?

What I really wanted to have was something like this:

ignore (NumberFormatException) {
    threads = Integer.parseInt(config?.threads as String)
}

This would ignore only a NumberFormatException if it was thrown, if something else was thrown, it would be thrown out of the present block.

As I expected this is pretty easy to implement in Groovy and after a brief search I couldn't really find anything in the standard libraries or the blogosphere at large.

Here's my implemenation with some example code:



Run this on the live GroovyConsole yourself.

What do you think? 

No comments:

Post a Comment