Lazy Error Handling in Java, Part 1: The Thrower Functor

How many try/catch blocks have you written in your day? Hundreds? Thousands? How many of the catch blocks look exactly the same? Is try/catch synonymous with copy/paste? Well, you may have written your last catch block. Follow me.

Let’s say that you’re coding in Java, and you want to call some code that might throw Exceptions, but you don’t want to be bothered with catching or throwing those exceptions in your code. Or you may want to call some existing code that doesn’t handle exceptions, passing it something that has methods which may throw exceptions. This can get ugly really fast, and you may end up with “throws Exception” declarations in places where you don’t want them, or try/catch blocks where you’re not sure whether to log the error or throw an unchecked exception, or what.

But, despair not. From very simple ingredients, we can conjure up powerful functional-style error handling to save the day. The first ingredient is a generic interface that declares, in its type expression, the exception thrown by its method:


  public interface Thrower<A, E extends Throwable>
   {public A extract() throws E;}
 

What we’re saying here is that there’s some operation preformed by extract() that returns an A and might throw an E. But the operation won’t take place (and won’t throw anything) until extract() is actually called.

What is such a thing useful for? Well, you could implement this interface, take parameters in a constructor, and perform some calculation in extract(). For example, reading a file and possibly throwing an IOException. But that’s a naive view of what generic interfaces are for. Thrower has higher aspirations than that. It’s not just an interface. It’s a functor. Observe:

  
  public static <A,B,E extends Throwable> F<Thrower<A,E>, Thrower<B,E>> fmap
    (final F<A,B> f)
    {return new F<Thrower<A,E>, Thrower<B,E>>()
      {public Thrower<B, E> f(final Thrower<A, E> a)
        {return new Thrower<B,E>()
          {public B extract() throws E
            {return f.f(a.extract());}};}};}
 

OK, so this is a static method on which class? It doesn’t matter, let’s say we put it in a utility class called Throwers (remembering to make it final and its constructor private). Just look at the type signature for now. The interface F<A,B> is from Functional Java, and it’s just an interface with one method B f(A a). So what fmap does is take a function from A to B, and return a function from Thrower<A,E> to Thrower<B,E>. In other words: fmap promotes the function f so that it works with computation that may throw checked errors, without f having been written to handle errors.

The implementation should be self-explanatory, albeit verbose (this is Java, after all). We construct an anonymous function to return, implementing its only method, which returns a new thrower which in turn yields the result of applying the function f to the contents extracted from the original thrower. It sounds a lot more complicated than it looks, so just read the code. All we’re doing is taking the A from a Thrower, turning it into a B, and wrapping that in another Thrower. If taking the A from the Thrower fails with an exception, we’ll carry that exception into the new Thrower.

The important thing to note here is that nothing actually happens until you call extract() on the resulting Thrower. Values of types F and Thrower are data structures that represent a computation to be carried out in the future. Anybody can pass Throwers around, but only a try/catch block, or a method that throws a Throwable of the right type may actually call extract() on it to run its computation and get its value. Java’s type system ensures that you can’t go wrong (although, as for unchecked exceptions, you’re on your own).

A simple example is in order. Just to illustrate the point, not to do anything very useful. This program reuses a function designed to operate on strings, so that it operates on operations that result in strings but might throw exceptions. The exception handling is done somewhere else, in ErrorHandler, outside of the main program, in an error handling library function called extractFrom, which we assume knows the right thing to do. Note that the main program has no try/catch block at all.

  
  public class Foo
   {public static void main (String[] args)
     {Thrower<String,IOException> readLn = new Thrower<String,IOException>()
       {public String extract() throws IOException
         {return new BufferedReader(new InputStreamReader(System.in)).readLine();}};
      System.out.println(ErrorHandler.extractFrom(Throwers.fmap(length).f(readLn)));}

    // A first-class function to get a String's length.
    public static F<String,Integer> length = new F<String,Integer>()
     {public Integer f(final String s)
       {return s.length();}};}
 

That’s right. You don’t have to handle exceptions at all in your code, even though you’re performing actions that throw exceptions. You just pass the buck to somebody who knows how to handle exceptions. It’s like outsourcing without the funny accents. OK, so you’re not really performing any IO actions, at least not syntactically speaking. ErrorHandler is doing that for you as well, since it’s the one calling extract() on the Thrower. This doesn’t make a difference to the compiled program except that the execution stack (and hence the stack trace, should things go terribly wrong) will look a bit different. If this makes you uncomfortable, here’s your hat and there’s the door. If you’ve ever used “Inversion of Control”, then this should be nothing new. In fact, in real life, you may want to inject something like ErrorHandler as a dependency, using Guice, or Spring, or something similar.

So there you go. That’s lazy error handling in Java, in a nutshell. But there’s more to come, as Thrower has higher aspirations still. It’s not just a functor. It’s a monad. We’ll talk about that in the next post.