Luca Fülbier Luca Fülbier - 1 month ago 6
Java Question

Documenting thrown RuntimeExceptions for Interfaces

I have the following interface:

public interface DataReceiver {
public Data getData();
}


The concrete Receivers have different sources for the data and therefore throw different exceptions:

public class DeviceDataReceiver implements DataReceiver {
// Gets data from some hardware device
// Exceptions include: DeviceNotConnected, DeviceNotLicensed, RequestTimeout, etc
public Data getData() { ... }
}

public class FileDataReceiver implements DataReceiver {
// Gets data from a file on disc
// Exceptions include: FileNotFound, BadFormat
public Data getData() { ... }
}


I documented these RuntimeExceptions in the according classes using the
@throws
Javadoc tag.

What i am struggling with is how to document the interface, since it will be the first thing a user of my library looks at, when he gets an error (I use the interface throughout my public API instead of the concrete classes). Documenting all the exceptions of the derived classes doesn't sound very appealing to me, since they have no relation at all.

Any best practices for this scenario?

Answer

What i am struggling with is how to document the interface, since it will be the first thing a user of my library looks at, when he gets an error (I use the interface throughout my public API instead of the concrete classes). Documenting all the exceptions of the derived classes doesn't sound very appealing to me, since they have no relation at all.

If you want to document these exceptions, I think you consider them as exception to handle for clients. If it is the case, why not using checked exceptions ?
I know there is two way of thinking about it but it is interesting in asking ourselves the question.

If you consider that these exceptions are not primordial to be checked and handled (or thrown), I also don't think you need to reference them in the interface. Besides, theoretically, interfaces should not be coupled to implementations in their specification.
However, you can specify in the interface methods what according to implementations, it may throw RuntimeException subclasses.
Besides, if you master the code source of these exceptions, maybe you could use an abstract class for ancestor exception(s) and make inheriting your subclasses to this abstract class. In this way, you could document this super exception in your interface.

Finally, your design encourage your clients to not program by interface when using DataReceiver subclasses because otherwise clients take the risk not to have specific javadoc and they will not directly see the specific exceptions that may throw methods of the implementation which use .
So, maybe you should also precise it in the interface.