Sunday, November 2, 2014

Disable Checked Exceptions?

I recently was frustrated by the necessity of annotating every function in the call chain in order to not handle an exception at the entry point to my code. The module I am working on accepts many different signatures for essentially the same method:

public static void doTransformation(Transformer t, Source in, Result out)
public static void doTransformation(Transformer t, InputStream in, Result out)
public static void doTransformation(Transformer t, InputStream in, OutputStream out)
public static void doTransformation(String t, InputStream in, OutputStream out)
public static void doTransformation(String xslt, String in, Writer out)
public static void doTransformation(String xslt, String in, OutputStream out)

Only the first actually does the transformation, but this can throw an exception from an external library, and all of the others call it directly or indirectly. I didn't want to annotate all of these with a throws declaration because I didn't know if I would have to switch out Transformer for something else or add more such methods in the future.

My first reaction was to leave off and go read a book; so I did that and then went to sleep. This morning I was looking at the code again and I was reminded of the first tool (or maybe second after abstraction) in the programmer's toolbox: indirection. Although a checked exception, if unhandled, can introduce a lot of unnecessary annotations into your code, you aren't obligated to use that exception throughout. All it took was wrapping that exception in my own derived from java's RuntimeException, and now it passes through to a place where I can deal with the exception appropriately.

I should have thought of such a simple solution right away — maybe I'll remember not to be writing code when I'm so tired in the future!

I happened upon this excellent blog post on exceptions in Java. Really, I can only vouch for the headings and the comments, but it's a very good summary.
~~~~