-1

I am writing a method to find the Xth largest entry in a list. The header is

<T extends Comparable<T>> T max(List<T> list, int rank) {...}

where rank is which place to find the max, (i.e. 0 is max, 1 is 2nd largest, ..., list.size() -1 is the min).

What Exception should I throw if a rank parameter is given that is >= list.size()? Is it an IndexOutOfBoundsException, because you are requesting the value of an index that is out of bounds, or would it be an IllegalArgumentException, because the IndexOutOfBoundsExeption is caused by the given parameters?

(I read this on when to use an IllegalArgumentException, but it just further confused me. In my case, the rank input could be user input or from a different place in the program, so I am not sure which is applicable.)

Aharon K
  • 312
  • 1
  • 10
  • 1
    I'd go `IllegalArgumentException` since the `IndexOutOfBoundsException` is subjective (kind'a). They never gave you an index, and I'm sure you could implement that method in a way that wouldn't cause one to happen. Whereas (provided your method's documentation says so) there's no way they can argue they didn't give an illegal argument. – BeUndead Dec 08 '20 at 17:20
  • The list acts as a map from N, the set of natural numbers to T. The value lies outside the domain of the map so you could argue its a domain error. – Jon Guiton Dec 08 '20 at 17:20

2 Answers2

0

You could create your own unchecked runtime exception that clearly identifies the problem and throw that: something like "RankIsGreaterThanListSizeException". The exception name provide more detail than either of the other options. You can include the provided rank and the list size in the message for extra context.

Michael McKay
  • 650
  • 4
  • 11
-2
public class StorageFileNotFoundException extends StorageException {

    /**
     * 
     */
    private static final long serialVersionUID = -4008604110260611040L;

    public StorageFileNotFoundException(String message) {
        super(message);
    }

    public StorageFileNotFoundException(String message, Throwable cause) {
        super(message, cause);
    }

}

here is an example

DV Singh
  • 1,038
  • 11
  • 16