What exception to throw when an important parameter/dependency is missing?

JavaOopException

Java Problem Overview


Take this method

/**
 * @return List of group IDs the person belongs to
 *
 */
public List<String> getGroups() {
    if (this.getId().equals("")) return null;
}

I would like to throw exception instead returning null, what's the exception to throw when an important parameter/dependency has not been set?

Java Solutions


Solution 1 - Java

I'd use IllegalArgumentException if the parameter/argument is controlled from outside, or IllegalStateException if the method is just called at a wrong moment (state). In your specific case I think it's the latter. A (dubious) alternative is NullPointerException.

This should however be explicitly documented in the @throws so that the user understands the reason.

Solution 2 - Java

Solution 3 - Java

I would use an IllegalStateException because the id is state of the owner. If the id would have passed as parameter, an IllegalArgumentException would be right.

Solution 4 - Java

If its not possible to ensure that the id is always set (by requiring it in the constructor for example, where you could check that a valid id has been passed) then I think the other suggestions to throw IllegalStateException are correct. But it would be better to try and ensure that your object can't get into this state in the first place if at all possible

Solution 5 - Java

Instead of throwing an exception, you should just return an empty list. If a dependency/parameter isn't met, then there are no results. From the comments and code posted, it looks like that's the expected behavior. If the id is empty, then there are no groups attached, thus an empty list.

Solution 6 - Java

I would create my own Exception type by extending Exception. That way calling functions can catch that particular Exception and handle it gracefully as appropriate. Note, you can do the same thing with just about anything that Extends Exception, but I prefer to create my own Exception classes so I can be very robust in my exception handling. This is, of course, up to you though.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPentium10View Question on Stackoverflow
Solution 1 - JavaBalusCView Answer on Stackoverflow
Solution 2 - JavaStefan KendallView Answer on Stackoverflow
Solution 3 - JavaArne BurmeisterView Answer on Stackoverflow
Solution 4 - JavaSam HolderView Answer on Stackoverflow
Solution 5 - JavaaephyxView Answer on Stackoverflow
Solution 6 - JavaJayView Answer on Stackoverflow