How can I document exceptions that are not initiated by a certain method / constructor, but may be rejected by another called?


Say I have a class with three constructors, like the one below:

public class ExampleClass {
    // constructor #1
    public ExampleClass(int a) {
        this(a, "aaa"); // "aaa" is just an arbitrary default for b

    // constructor #2
    public ExampleClass(String b) {
        this(2, b); // 2 is just an arbitrary default for a

    // constructor #3
    public ExampleClass(int a, String b) {
        // a has an arbitrary minimum value of 3
        // b has an arbitrary minimum length of 3
        if (a < 2 || b.length() < 2) {
            throw new IllegalArgumentException("a and b cannot be less than 2");

        // ...

In this case, I have three constructors. The third of which is sort of the primary constructor, the others simply provide defaults so the class can be constructed with only one value given instead of both. I'm attempting to write documentation for such classes via JavaDoc. If I were to write the documentation for either the first or second constructors, would I use the @throws tag to document the potential IllegalArgumentException? Or should I save documenting the IllegalArgumentException for the third constructor's documentation only? In that case, what would be the best, most appropriate way of expressing that a must be above 2 or that b must be longer than 2 characters? How would I state that an IllegalArgumentException could be thrown without documenting it with @throws ?

All three of your constructors do throw an exception (you can verify this empirically) - you can't expect a consumer of your code to know what goes on under the covers (ie whether the arguments are checked within the constructor, or by some method called by the constructor). As such, you should document all three constructors.

It's always nice to not repeat yourself, but not always practical - Javadoc can't express the relationship you want, so you need to express it long hand.