Which exception should be thrown by a method that accepts multiple arguments when the arguments given are invalid when given together?
As an example, consider
public Bar DoSomething(Foo f1, Foo f2)
{
//implementation...
}
where completing the operation is contingent upon some relationship or similarity between f1
and f2
(if arrays/collections, they must be the same size; if athletes, they must be on the same team/opposing teams; etc.).
Each argument is a valid argument for the operation, but they are not valid together. Example:
public MatchResult PlayMatch(Player a, Player b)
{
if(a.Team == b.Team)
{
//Throw exception here, since players must be on different teams
}
//Play match, determine winner
}
Throwing an ArgumentException
seems incorrect, since it implies that one of the arguments is invalid rather than that the pair of arguments together is invalid.
You don't have to necessary throw an exception. In my opinion, this even should not throw an exception because is a deep part of your matching logic. I would just let matching fail (return zero or whatever you do) instead and mentioned this fact in documentation - something like "Compares two players from different teams." which implies that comparing players from the same team will result in fail.