[Edit: 28 Nov 2010] Updated the example and added another to clarify usage.
When we know that a function might (or might not) throw an exception we need to prepare for the error condition in advance. Clojure inter-operates with Java and supports catching and throwing of exceptions:
However, in practice we often need to catch an exception and store it temporarily and probably look for few more such error conditions so that we can treat them collectively. For an example, validating user input with multiple data elements. Trying to scale try-catch to such scenarios is hard and clunky, so let's try an alternative approach - non-breaking error handling.
Let's see how to use it:
Now trying them out:
So a possible error-condition got conveniently folded into a vector at a predictable index, without breaking the flow of control at the consumer end. Now let us see another example where the underlying functionality might throw an exception.
Such a function can be used to read a configuration file and fall back on defaults if safe-slurp returns nil:
Summarily, I would like to note that a try-catch block forces one to think imperatively. Fortunately, there is a solution -- use 'maybe'. Please post your comments about it. You may like to follow me on Twitter.