2-Jan-04 (Created: 2-Jan-04) | More in 'CS-Java'

Interfaces and checked exceptions are like butter and sand: they don't mix well

Exceptions is one area where opinions differ considerably. Not only about the usage of exceptions but also about the need and utility of checked exceptions. I hear arguments from various sides. They all seem valid in their own right. I use interfaces heavily in my coding practice. Particularly in my J2EE tool Aspire. Over time I paid dearly for not declaring exceptions on these interfaces. Primarily because I would start out thinking that this interface is too simple and not declare an exception. Subsequent implementation of these interfaces will necessitate apis calls that throw checked exceptions. With out changing the interface either I need to throw a converted chained runtime exception or change the interface to include a politically correct middle of the road exceptions suitable for that interface

Realizing this mistake one too many times I have decided to pay special attention to declaring exceptions with interface methods. I would probably stop and think twice if I see an interface method that does not have an exception defined.

Interfaces as such, even when they have exceptions defined, have an issue with exceptions. Because these interface methods must be able to pass through the exceptions from the implementations. Chained exceptions have atleast solved this problem consistently. Nevertheless unless you define at least one checked exception as part of an interface you have no exception to piggy back on.

I will just have to monitor this new resolution I have and see how this rule fares in my future designs.

Now that interfaces will most likely have exceptions, the question is what should they be? One might be inclined to come up with a single exception for the entire application and use it as a place holder. But in this case you are only a step above from using the base "Exception" itself. I am not sure if this is the right way. Perhaps one can assume that a collection of interfaces work together to implement a concept in your application, such as lets say 'masterpages'. Then all the relevent interfaces that are created for this purpose will through a "MasterPageException". For now I will go with this and see what happens.