Technical Articles by Sony Mathew, Software Architect, Twin Cities, MN

Tuesday, April 27, 2010

Checked vs. Runtime Exception

This age old argument has been raised again by many recently and like them I decided to stamp my opinion out on the blog-o-sphere as well. I picked up where Cedric Beust left off.

I used to be a proponent of checked exceptions and had strongly stood my ground for a long time but I am now older and more forgiving. Whether an exception is recoverable or Not is mostly contextual. One call path may decide to recover while another may decide to fail from the same exception just as they might decide independent courses of action based on a return value.  An exception should only be a vehicle for information and abstracted as such (which is why I think interfaces for exceptions should have existed) while allowing callers under different contextual paths to process the exception as they choose best.

Additionally, many classes are implementations of one or more interfaces. We don't always have control over interfaces we implement and even when we do we should treat them as immutable as much as possible - mostly because interfaces exist to adapt various implementations to a general contract. When conforming an implementation to one or more general contracts - checked exceptions just cannot be declared consistently and in most cases not even possible. Given this and and the contextual nature of exceptions - it follows naturally that we only need the RuntimeException - however the traditional meaning of the RuntimeException will no longer be valid under this new paradigm - instead it gets redefined as merely a vehicle for Alternate information.