What exception to throw when an important parameter/dependency is missing?
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?
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.
How about IllegalStateException?
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.
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
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.
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.
精彩评论