4

Since Kotlin hasn't got checked exception, what's the correct way to document exception expected to be thrown by an interface method? Should I document it in the interface or in the implementing class (only if the concrete method actually throws it)?

Fraquack
  • 93
  • 1
  • 4
  • You could use the `@Throws` annotation. IMO makes most sense to place this on the interface methods. – Oliver Charlesworth Nov 27 '17 at 13:23
  • If it's on the implementation, then a function taking the interface won't know whether it can throw or what it can throw. Worse would be two implementations throwing different things. See: [LSP](https://en.wikipedia.org/wiki/Liskov_substitution_principle) – chris Nov 27 '17 at 13:25

1 Answers1

1

Since clients program against the interface, I'd suggest the documentation to be made in the Javadoc/KDoc of that interface. Whether you actually should document them is discussed in this thread for example:

Oracle recommends:

If it's so good to document a method's API, including the exceptions it can throw, why not specify runtime exceptions too?
Runtime exceptions represent problems that are the result of a programming problem, and as such, the API client code cannot reasonably be expected to recover from them or to handle them in any way. Such problems include arithmetic exceptions, such as dividing by zero; pointer exceptions, such as trying to access an object through a null reference; and indexing exceptions, such as attempting to access an array element through an index that is too large or too small.
Runtime exceptions can occur anywhere in a program, and in a typical one they can be very numerous. Having to add runtime exceptions in every method declaration would reduce a program's clarity.

So if the information is useful for a client it should be documented (i.e. if the client can handle it, e.g. IOException). For "regular" runtime exceptions such as an IllegalArgumentException I would say "no", do not document them.

s1m0nw1
  • 76,759
  • 17
  • 167
  • 196