Luca Fülbier Luca Fülbier - 3 months ago 13
Java Question

Java interface implementations throw different exceptions

I have the following situation:

public interface DataReceiver {
public Data getData();
}

public FileDataReceiver implements DataReceiver {
public Data getData() throws FileNotFoundException {..}
}

public DeviceDataReceiver implements DataReceiver {
public Data getData() throws DeviceConnectionException {..}
}


This code doesn't compile when any of my thrown exceptions is a checked exception. How do you handle this?

Answer

You can't "widen" the implementation of an interface, compared to the interface.

So, if you changed your interface to

public interface DataReceiver {
  public Data getData() throws FileNotFoundException, DeviceConnectionException ;
}

then your implementing classes wouldn't widen the interface, but restrict it. And that is fine.

On the other hand, that would force you to put all kinds of different checked exceptions on your interface; which might or might not be a not a good design choice. As you force your client code to deal with all those interfaces!

You could:

  1. Create your own special exception class; and throw instances of that (for example: wrapping around the specific exceptions thrown by the various implementations)
  2. Consider using more than one interface; or more than one method within the existing interface.

Finally, on the comment that exceptions are unchecked: my personal "solution" is: I do not put unchecked exceptions on the throws list. Never ever. What I do instead: "on the surface of my class" - meaning on "public methods" that might be throwing such unchecked exceptions ... I do a javadoc "@throws" and explain why/when/which unchecked exception might come out of this method.

Comments