The question to ask yourself first is whether you should be throwing at all and then, if so, whether it should be a checked or unchecked exception.
Unfortunately, there's no industry best practice on deciding these things, as shown by this StackOverflow answer:
http://stackoverflow.com/questions/499437/in-java-when-should-i-create-a-checked-exception-and-when-should-it-be-a-runtim/499458#499458
Nevertheless, there are some key considerations:
Your design/vision for how this method is supposed to work (Is it reasonable/normal for the method to be called with 0-size list)?
Consistency with other methods in the class/package
Compliance with your applicable coding standard (if any)
My opinion:
Return Double.NAN
or 0 If calling the method with a 0-size list is reasonable/expected/normal, I'd consider returning Double.NAN
or 0
if 0
is appropriate for your problem domain.
Throw anIllegalArgumentException
If my design says that checking for an empty List is strongly the responsibility of the caller and the documentation for the method is going to clearly state that it is the responsibility of the caller, then I'd use the standard unchecked IllegalArgumentException
.
Throw a custom checked exception If the method is part of a statistics package or library where several statistics functions need to deal with an possible empty data set, I'd think this is an exception condition that is part of the problem domain. I'd create a custom (probably checked) exception (e.g. EmptyDataSetException
) to be part of the class/package/library and use it across all applicable methods. Making it a checked exceptions helps remind the client to consider how to handle the condition.